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

Lai*_*ith 6 c++ decltype auto type-deduction

我观看了一段关于汽车和decltype的类型演绎规则的视频,由Scott Meyers解释......他解释了以下内容

// decltype(lvalue expr) => reference to the type of the expression
// decltype(lvalue name) => type of the name
Run Code Online (Sandbox Code Playgroud)

我理解这些规则......但他没有解释以下内容

// decltype(rvlaue expr) => ???
Run Code Online (Sandbox Code Playgroud)

所以我试着通过练习来理解它,所以我做了以下几点

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
Run Code Online (Sandbox Code Playgroud)

现在神奇了

decltype(std::move(x)) t4 = x;  // Error t4 is int&& ... compiler says
Run Code Online (Sandbox Code Playgroud)

是不是std :: move(x)一个右值表达式?为什么decltype推导t4到int &&不仅仅是像上面的例子?rvalue表达式的decltype类型推导有哪些规则?

Nat*_*ica 4

decltype根据使用的类型,其行为有所不同

如果表达式的值类别是 xvalue,则 decltype 产生 T&&;

如果表达式的值类别是左值,则 decltype 产生 T&;

如果表达式的值类别是纯右值,则 decltype 产生 T。

正如您所看到的,它对右值有两种不同的行为。如果右值是 xvalue,则我们得到T&&,否则它是纯右值,我们得到T

现在,如果我们看一下,std::move我们会发现它返回 anxvalue作为返回 isT&&和 not Tstd::move(x)xvalue 也是如此,并被正确推导为int&&