【问题标题】:What are the type deduction rules of decltype(rvalue expr) ?decltype(rvalue expr) 的类型推导规则是什么?
【发布时间】:2016-08-07 10:29:51
【问题描述】:

我看过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类型推导规则是什么?

【问题讨论】:

  • 注意std::move的签名:std::remove_reference_t<T>::type&& move(T&&);。它返回一个右值引用,而不是按值。
  • 可以参考参考资料。谷歌文档大约需要十秒钟。

标签: c++ auto decltype type-deduction


【解决方案1】:

decltype 的行为因所使用的类型而异

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2023-01-14
    • 2017-03-18
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 2017-05-29
    相关资源
    最近更新 更多