【发布时间】:2016-10-21 02:26:52
【问题描述】:
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 的常量 扣除。
我认为这意味着
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 &?
【问题讨论】:
-
回复:“为什么不是
rxconst int &?”:可以,如果你写f<const int &>(rx)(而f<int &>(rx)无效)。但是,就此而言,您也可以写f<const int &>(x)。所以rx的引用与模板参数推导无关;它被视为与const int一样。
标签: c++ templates pointers reference template-argument-deduction