gpt4 book ai didi

c++ - 说明乘以 2 个常量整数时的 decltype 输出

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:58 24 4
gpt4 key购买 nike

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 with 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 限定,但 decltype(i*i)i*i 的表达式创建类型为 i< 的非物化纯右值 与非 cv-qualified,prvalue 没有明确的常量概念。您的代码产生的结果与:

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

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

5.2.8.5 - If the type of the expression or type-id is a cv-qualified type, the result of the typeid expression refers to a std::type_info object representing the cv-unqualified type.

关于c++ - 说明乘以 2 个常量整数时的 decltype 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39561074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com