【发布时间】:2021-05-22 07:36:14
【问题描述】:
#include <utility>
template<typename T>
concept IsWritable = requires(T& obj)
{
obj = 0;
};
template<typename T>
void f(T&)
{}
int main()
{
static_assert(IsWritable<int&&>); // ok
int n = 0;
f(std::move(n)); // error
}
GCC 错误信息:
error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type
'std::remove_reference<int&>::type' {aka 'int'}
为什么我不能将左值引用绑定到右值,而概念可以?
【问题讨论】:
-
在概念中左值引用与右值的绑定在哪里?
-
严格来说,概念的 requires 表达式不能将左值引用绑定到右值,因为它是编译时评估。我只是想知道:为什么 C++20 标准允许违反直觉的行为?
-
如果
T是int&&,那么int&& &的类型是什么?请注意,这里不是通用参考。 -
@xmllmx,
int&& &的类型是int&,因为引用折叠适用于引用,而不仅仅是通用引用。 -
@xmllmx,因为您将右值绑定到非
const引用。
标签: c++ standards c++20 rvalue-reference c++-concepts