c++ - 为什么不将模板类型参数推断为 'const' ?

标签 c++ templates constants type-parameter

<分区>

Possible Duplicate:
deducing references to const from rvalue arguments

如果我有

template<class T>
void foo(T &) { }

我称它为 foo((const int)5),鉴于参数是 const int,为什么编译器不自动推断 Tconst 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/

相关文章:

c++ - Xcode 使用 C++ 在控制台中不显示任何内容

c++ - 如何消除仅返回类型不同的函数模板的歧义?

c++ - 我可以在成员函数上使用 boost::enable_if 吗?

c++ - 将值与结构成员进行比较的问题

c++ - 如何将常量中的值设置为struct c++

c++ - ld.exe 找不到-lGL

c++ - 为 iOS 创建 Qt 5.1 应用程序

c++ - 我可以在类定义中放置 "non-static blocks"代码吗?

c++ - 无捕获的 lambda 是结构类型吗?

constants - 将 ⊤ ("down tack") 字符定义为我可以在我的程序中使用的常量