decltype(右值表达式)的类型推导规则是什么
What are the type deduction rules of decltype(rvalue expr) ?
我看过Scott Meyers解释的关于auto和decltype的类型推导规则的视频。。。他解释了以下
// decltype(lvalue expr) => reference to the type of the expression
// decltype(lvalue name) => type of the name
我理解这些规则。。。但他没有解释下面的
// decltype(rvlaue expr) => ???
所以我试着通过练习来理解它,所以我做了下面的
int x = 8;
int func(); // calling this function is rvlaue expr ...
decltype(32) t1 = 128; // Ok t1 is int
decltype(64) t2 = x; // Ok t2 is int
decltype(func()) t3 = x; // Ok t3 is int ... obviously
现在神奇的
decltype(std::move(x)) t4 = x; // Error t4 is int&& ... compiler says
std::move(x)不是右值表达式吗?为什么decltype将t4推导为int&;不只是像上面的例子那样的int?右值表达式的decltype类型推导规则是什么?
decltype
根据上使用的类型表现不同
如果表达式的值类别是xvalue,则decltype产生T&;;
如果表达式的值类别是左值,则decltype产生T&;
如果表达式的值类别是prvalue,则decltype产生T.
正如你所看到的,它对右值有两种不同的行为。如果右值是一个xvalue,那么我们得到T&&
,否则它是一个prvalue,我们得到T
。
现在,如果我们看看std::move
,我们会发现它返回一个xvalue
,因为返回的是T&&
而不是T
。因此std::move(x)
是一个x值,并被正确地推导为int&&
相关文章:
- C++中的严格别名规则和类型别名
- 使用C++11标准的哪些规则来确定({..})中表达式的类型
- 如何在不违反类型别名规则的情况下解释消息负载?
- 强制转换为不相关的引用类型是否违反严格的别名规则?
- POD 类型的二进制 I/O 如何不违反别名规则
- 在 Objective-C++ 中应用于__weak指针时,通过关键字推导类型"auto"规则是什么?
- 有关不完整类型的Sfinae的特殊规则
- 精神X3,如何获得属性类型以匹配规则类型
- C++20 中的严格别名规则是否允许标准 c++ unicode 字符和下划线类型之间"reinterpret
- 初始化中的模板转换运算符类型推导规则是什么?
- 将临时值存储为某种数据类型时,算术运算的标准规则是什么
- MISRA C++规则 14-5-1:在与类型关联的命名空间中声明的泛型函数模板的名称
- 本地类规则是否与c++14返回类型推导一致
- 将字符阵列施放到另一种类型中是否违反了严格的确定规则
- 要求将各种类型的各种类型传递给微控制器上的规则引擎.施放问题
- 隐式数值类型转换的规则
- 在makefile中更改构建规则以构建多种文件类型
- 用删除类型的指针的stof()/stoi()将打破严格的确定规则
- 显式类型转换vs使用类型规则
- 如何从另一个仅静态选择满足特定类型规则的索引的元组实例创建元组实例