c++ - 为什么引用模板参数不推导出 const?

标签 c++ templates reference type-deduction

我编写了以下代码,对于指针,它显示了正确的参数类型,但是当我使用引用时,它只显示 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

… 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&Tcv 限定被删除。

后者可能是为了不区分 T&T——它们产生相同的结果。

关于c++ - 为什么引用模板参数不推导出 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37412265/

相关文章:

java - 如何避免Runnable回调泄漏?

android - 在android中生成签名apk时 Unresolved reference 错误

c++ - #define 打印(消息)std::cout << 消息 << std::endl

c++ - "Static polymorphism with Qt signal/slot: What is wrong?"

c++ - Box2d 错误 C :\filepath\box2D. lib 不是有效的 Win32 应用程序

templates - 可扩展的临时多态性? (C++11)

c++ - 是明确的特化模板吗?

c++ - thread_group 中的一个线程没有被中断

c++ - 如何更改 MSVC++ 的 std::tuple 支持的模板参数的数量?

PHP:通过引用实例化类?