gpt4 book ai didi

c++ - 为什么 "decltype(i+j)"的结果不是右值引用?

转载 作者:IT老高 更新时间:2023-10-28 22:08:43 26 4
gpt4 key购买 nike

我正在尝试为导致右值的操作提出一个简单的示例。

这个测试用例应该可以工作,但令人惊讶的是(对我而言),添加两个 int 的结果不是右值(引用)。我在这里错过了什么?

void test(int i, int j)
{
// this assert should pass, but fails:
static_assert(std::is_same<decltype(i + j), int&&>(), "i + j should be a rvalue");
// this assert passed, but should fail:
static_assert(std::is_same<decltype(i + j), int>(), "this assert should fail...");
}

最佳答案

i + jprvalue expression ,

A prvalue ("pure rvalue") expression is an expression that does not have identity and can be moved from.

a + b, a % b, a & b, a << b, and all other built-in arithmetic expressions;

不是 xvalue ,

An xvalue ("expiring value") expression is an expression that has identity and can be moved from.

还有 decltype specifier为纯右值生成 T,而不是 T&&

a) if the value category of expression is xvalue, then decltype yields T&&;
b) if the value category of expression is lvalue, then decltype yields T&;
c) if the value category of expression is prvalue, then decltype yields T.

您可以通过 std::move:

使其成为 xvalue
static_assert(std::is_same<decltype(std::move(i + j)), int&&>(), "std::move(i + j) is a xvalue then this static_assert won't fail"); 

关于c++ - 为什么 "decltype(i+j)"的结果不是右值引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36762832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com