c++ - decltype(rvalue expr) 的类型推导规则是什么?

标签 c++ auto decltype type-deduction

我看过一段关于 auto 和 decltype 的类型推导规则的视频,由 Scott Meyers 解释......他解释了以下内容

// 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根据使用的类型不同表现不同

if the value category of expression is xvalue, then decltype yields T&&;

if the value category of expression is lvalue, then decltype yields T&;

if the value category of expression is prvalue, then decltype yields T.

如您所见,它对右值有两种不同的行为。如果右值是一个 xvalue,那么我们得到 T&&,否则它是一个 prvalue,我们得到 T

现在,如果我们看一下 std::move我们看到它返回一个 xvalue,因为返回的是 T&& 而不是 T。所以 std::move(x) 是一个 xvalue 并且被正确推导为 int&&

关于c++ - decltype(rvalue expr) 的类型推导规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36647330/

相关文章:

c++ - 解析以扩展 SMTP (ESMTP) 结尾的响应

c++ - 'auto'之前是什么?

c++ - 在模板中使用第一种类型的类成员的类型

c++ - Xcode:错误:函数样式强制转换或类型构造的预期 '('

c++ - 将派生指针隐式转换为其相应基址的引用

c++ - 将有符号整数转换为二进制 float 是否比逆运算便宜?

c++ - 为什么即使调用了析构函数,C++11 中的分离线程也能执行

c++ - 如何在 C++11 中使用 lambda 自动参数

C++ auto on int16_t 强制转换为整数

c++ - C++ 中 decltype(this) 的类型是什么?