template <typename T>
void f(T t)
{}
int x = 1;
const int & rx = x;
const int * px = &x;
f(rx); // t is int
f(px); // t is const int *, instead of int *, WHY???
我现在有些困惑。根据《Effective Modern c++》所述,
重要的是要认识到const只对按值传递的参数无效。正如我们所看到的那样,对于引用或指向常量的指针参数,expr的const性质在类型推导期间得以保留。
我认为它的意思是:
template <typename T>
void f(T * t)
{}
f(px); // t is const int *
template <typename T>
void f(T & t)
{}
f(cx); // t is const int &
template <typename T>
void f(T t)
{}
f(value); // const or volatile of value will be ignored when the type of the parameter t is deduced
因此,我认为当f(px)
上方时,t
应该是int*
,但实际上它是const int*
。
为什么引用的const
被忽略了,而指针的const
没有被忽略呢?
或者说,为什么rx
不是const int&
?
rx
不是const int &
?”:如果您编写f<const int &>(rx)
,它可以是const int &
(而f<int &>(rx)
将无效)。但是,同样地,您也可以编写f<const int &>(x)
。因此,rx
的引用性与模板参数推断无关;它被视为只是一个const int
。 - ruakh