C ++ 11:为什么将右值引用参数隐式转换为左值 [英] C++11: Why rvalue reference parameter implicitly converted to lvalue
问题描述
以下是我的问题的简化代码,
Following is the simplistic code of my problem,
void overloaded (int&& x) {
cout << "[rvalue]";
}
template <class T>
void fn (T&& x) {
overloaded(x);
}
int main() {
fn(0);
return 0;
}
我遇到了编译错误
无法将'
int
'左值绑定到'int& '
overloaded(x);
我很困惑, x
作为右值引用传递到 fn()
中。但是为什么 fn()
中的 overload()
调用会抱怨 x
是左值吗?
I am confused here, x
is passed as a rvalue reference into fn()
. But why the overload()
call in fn()
complains x
is a lvalue?
推荐答案
一个, x
参数 fn
不是r值引用,它是通用引用 (是的,这相当令人困惑)。
One, the x
argument to fn
isn't an r-value reference, it's a "universal reference" (yes, this is rather confusing).
二,给对象命名后,该名称不是r值,除非使用 std :: move
显式固定(将其命名为r值引用,始终),或使用 std :: forward
(在通用引用的情况下将其转换回其原始类型)。如果要避免投诉,请使用 std :: forward
转发为原始类型:
Two, the moment you give an object a name, that name is not an r-value unless explicitly "fixed", either with std::move
(to make it an r-value reference, always), or with std::forward
(to convert it back to its original type in the case of universal references). If you want to avoid the complaint, use std::forward
to forward as the original type:
template <class T>
void fn (T&& x) {
overloaded(std::forward<T>(x));
}
这篇关于C ++ 11:为什么将右值引用参数隐式转换为左值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!