将 decltype 的表达式从常量左值转换为右值是否也会丢弃“const”?
Is converting decltype's expression from constant l-value into an r-value discards `const` too?
这里我想知道类型说明符 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
为什么 y
只有类型 int
而不是 const int
?
除了引用运算符,const
限定符是否也将常量左值转换为右值丢弃?
为什么typeid
显示x
的类型只是i
而不是const int&
?
将 int
(0
是类型 int
的八进制文字)添加到 const int&
时得到的表达式类型是 int
。所以 y
的类型是 int
.
关于你的第二点,在 左值到右值的转换过程中 ,non-class 类型的 const
作为 non-class 类型的右值被丢弃不能是 cv-qualified.
关于你的最后一点,在所有情况下,cv-qualifiers 都会被 typeid
忽略。参见 https://en.cppreference.com/w/cpp/language/typeid
> 为什么 y 的类型只有 int 而不是 const int?
因为(rci + 0)
是一个纯右值,原始类型的纯右值已经去掉了const。
> 除了引用运算符、const 限定符外,将常量左值转换为右值是否也丢弃?
对于 non-class 类型,const 限定符被丢弃。来自 standard:
7.3.1.1
[...] If T is a non-class type, the type of the prvalue is the cv-unqualified version of T.
> 为什么typeid显示x的类型只是i而不是const int&?
来自cppreference:
In all cases, cv-qualifiers are ignored by typeid (that is, typeid(const T) == typeid(T)).
这里我想知道类型说明符 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
为什么
y
只有类型int
而不是const int
?除了引用运算符,
const
限定符是否也将常量左值转换为右值丢弃?为什么
typeid
显示x
的类型只是i
而不是const int&
?
将 int
(0
是类型 int
的八进制文字)添加到 const int&
时得到的表达式类型是 int
。所以 y
的类型是 int
.
关于你的第二点,在 左值到右值的转换过程中 ,non-class 类型的 const
作为 non-class 类型的右值被丢弃不能是 cv-qualified.
关于你的最后一点,在所有情况下,cv-qualifiers 都会被 typeid
忽略。参见 https://en.cppreference.com/w/cpp/language/typeid
> 为什么 y 的类型只有 int 而不是 const int?
因为(rci + 0)
是一个纯右值,原始类型的纯右值已经去掉了const。
> 除了引用运算符、const 限定符外,将常量左值转换为右值是否也丢弃?
对于 non-class 类型,const 限定符被丢弃。来自 standard:
7.3.1.1
[...] If T is a non-class type, the type of the prvalue is the cv-unqualified version of T.
> 为什么typeid显示x的类型只是i而不是const int&?
来自cppreference:
In all cases, cv-qualifiers are ignored by typeid (that is, typeid(const T) == typeid(T)).