我编写了以下代码,对于指针,它显示了正确的参数类型,但是当我使用引用时,它只显示 int
而没有 const
。为什么?
template <typename T>
void increment(T& x)
{
std::cout << "Argument type is : " << typeid(x).name() << std::endl;
//x = x + 1;
}
template <typename T>
void increment(T* x)
{
std::cout << "Argument type is : " << typeid(x).name() << std::endl;
//x = x + 1;
}
int main()
{
const int x = 0;
const int y = x;
increment(x);
increment(&y);
}
输出:
Argument type is : int
Argument type is : int const *
你能解释一下为什么 const
没有显示引用吗?
最佳答案
C++11 §5.2.8/4
C++11 §5.2.8/5” … If the type of the type-id is a reference to a possibly cv-qualified type, the result of the
typeid
expression refers to astd::type_info
object representing the cv-unqualified referenced type. …
” The top-level cv-qualifiers of the glvalue expression or the type-id that is the operand of
typeid
are always ignored.
本质上,任何顶级 const
都被删除了,就像正式函数参数类型 wrt 一样。结果函数类型,以及引用类型 T&
中 T
的 cv 限定被删除。
后者可能是为了不区分 T&
和 T
——它们产生相同的结果。
关于c++ - 为什么引用模板参数不推导出 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37412265/