澄清了当2个const int相乘时的decltype输出

clarification of decltype output when multiplying 2 const ints

本文关键字:decltype 输出 int 2个 const      更新时间:2023-10-16
int main()
{
 const int a = 1;
 const int b = 2;
 typedef decltype(a*b) multiply_type;
 cout << typeid(multiply_type).name() << endl;
 return 0;
}

程序的返回值是multiply_type为int。我很惊讶。我期望类型推导产生const int,由于表达式产生一个pr值,因此结果类型将是const int。

PS:对于auto,返回值将是int,因为它去掉了const限定符。

有没有人知道为什么multiply_type是int而不是const int与decltype ?

编辑:添加了一个额外的例子,也与cv-qualifier有关。

#include<iostream>
#include<typeinfo>

using namespace std;
struct Details
{
    int m_age;
};
int main()
{
 const Details* detail = new Details();
 typedef decltype((detail->m_age)) age_type;
 cout << typeid(age_type).name() << endl;
 int a = 1;
 age_type age = a;
 age = 10; // This is not possible. Read only. 
 cout << typeid(age).name() << endl; // This returns the type as int though. Then why is 20 not possble ?
 return 0;
}
编辑2:检查我们的链接。http://thbecker.net/articles/auto_and_decltype/section_07.html'
int x;
const int& crx = x;
/ The type of (cx) is const int. Since (cx) is an lvalue,
// decltype adds a reference to that: cx_with_parens_type
// is const int&.
typedef decltype((cx)) cx_with_parens_type;` 

decltype按实值计算,decltype(i)icv-qualified左值,结果声明类型为cv-qualified,但decltype(i*i)i*i的表达式创建了类型为i且非cv-qualified的非实体化右值,右值没有明确的一致性概念。您的代码产生的结果与

相同
using T = const int;
static_assert(is_same<int, decltype(0)>(), "Failed");

typeid没有显示cv资格的事实是因为它们被忽略了:

5.2.8.5 -如果表达式的类型或type-id是一个cv-qualified类型,则typeid表达式的结果指向一个std::type_info对象,表示该cv-qualified类型。