<分区>
Possible Duplicate:
deducing references to const from rvalue arguments
如果我有
template<class T>
void foo(T &) { }
我称它为 foo((const int)5)
,鉴于参数是 const int
,为什么编译器不自动推断 T
是 const int
?
<分区>
Possible Duplicate:
deducing references to const from rvalue arguments
如果我有
template<class T>
void foo(T &) { }
我称它为 foo((const int)5)
,鉴于参数是 const int
,为什么编译器不自动推断 T
是 const int
?
最佳答案
根据 C++03 标准第 2.12.1.2 条,整数文字的类型是 int
,而不是 const int
。
The type of an integer literal depends on its form, value, and suffix. If it is decimal and has no suffix, it has the first of these types in which its value can be represented: int, long int;...
更新
另一个相关的类型推导规则可能是 14.8.2.1.2。
If P is not a reference type:
[...]
— If A is a cv-qualified type, the top level cv-qualifiers of A’s type are ignored for type deduction.
If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction.
If P is a reference type, the type referred to by P is used for type deduction.
OP 提供的代码甚至无法编译,因为将非常量引用绑定(bind)到右值是非法的。
关于c++ - 为什么不将模板类型参数推断为 'const' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11931452/