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

标签 c++ c++11 c++14 decltype

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/

相关文章:

c++ - std::abs(0u) 格式不正确吗?

c++ - 定义一个类 `MultiInherit<MyTuple<X1,X2,...>>`继承自 `X1,X2,...`

c++ - 在库中隐藏类的使用

c++ - GCC 似乎错过了简单的优化

c++ - 使用 C++ 在 Chrome 中获取事件选项卡 URL

c++ - std::tuple 参数中的类型顺序有什么影响吗?

c++ - 如何有条件地为 Eclipse 中的交叉编译项目包含两个相同版本的不同名称的库?

c++11 - 在 c++11 中,dynamic_cast 是否返回 nullptr 或 0?

c++ - 尽管右侧出现异常,但 C++ 中的赋值仍然存在

c++ - 标准 C++11 是否保证 std::async(std::launch::async, func) 在单独的线程中启动 func?