decltype(右值表达式)的类型推导规则是什么

What are the type deduction rules of decltype(rvalue expr) ?

本文关键字:类型 规则 是什么 表达式 decltype      更新时间:2023-10-16

我看过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&&