首页 > 解决方案 > 将 decltype 的表达式从常量左值转换为右值是否也会丢弃 `const`?

问题描述

在这里我想知道类型说明符是如何decltype工作的:

const int& rci = 5;// const ref bound to a temporary
decltype (rci) x = 2;
decltype (rci + 0) y = 10;
// ++x; // error: increment of read-only reference ‘x’|
++y; // why does this work

std::cout << typeid(x).name() << std::endl; // i
std::cout << typeid(y).name() << std::endl; // i

标签: c++c++11constantsdecltype

解决方案


> 为什么 y 只有 int 类型而不是 const int?

因为(rci + 0)是纯右值,原始类型的纯右值已被 const 剥离。

> 除了引用运算符 const 限定符之外,将常量左值转换为右值是否也会丢弃?

对于非类类型,const 限定符被丢弃。从标准

7.3.1.1
[...] 如果 T 是非类类型,则纯右值的类型是 T 的 cv 非限定版本。

> 为什么 typeid 显示 x 的类型只是 i 而不是 const int&?

cppreference

在所有情况下,typeid 都会忽略 cv 限定符(即 typeid(const T) == typeid(T))。


推荐阅读