澄清了当2个const int相乘时的decltype输出
clarification of decltype output when multiplying 2 const ints
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)
中i
为cv-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类型。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++decltype和圆括号-为什么
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 来自 decltype 的意外输出类型
- 澄清了当2个const int相乘时的decltype输出