为什么引用模板参数不推导出 const?
Why is reference template argument not deducing const?
我写了下面的代码,对于指针,它显示了正确的参数类型,但是当我使用引用时,它只显示 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
没有显示参考吗?
If type is a reference type, the result refers to a std::type_info
object representing the referenced type.
和
In all cases, cv-qualifiers are ignored by typeid (that is, typeid(T)==typeid(const T)
)
(更准确地说是顶级const
)T
当然被推导为const int
。
标准段落为[expr.typeid]/4
和[expr.typeid]/5
C++11 §5.2.8/4
” … If the type of the type-id is a reference to a possibly cv-qualified type, the result of the typeid
expression refers to a std::type_info
object representing the cv-unqualified referenced type. …
C++11 §5.2.8/5
” 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
– 它们产生相同的结果。
我写了下面的代码,对于指针,它显示了正确的参数类型,但是当我使用引用时,它只显示 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
没有显示参考吗?
If type is a reference type, the result refers to a
std::type_info
object representing the referenced type.
和
In all cases, cv-qualifiers are ignored by typeid (that is,
typeid(T)==typeid(const T)
)
(更准确地说是顶级const
)T
当然被推导为const int
。
标准段落为[expr.typeid]/4
和[expr.typeid]/5
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
– 它们产生相同的结果。