[英]lvalue binding to rvalue reference
I am trying to understand how lvalues bind to rvalue references. 我试图了解左值如何绑定到右值引用。 Consider this code: 考虑以下代码:
#include <iostream>
template<typename T>
void f(T&& x) {
std::cout << x;
}
void g(int&& x) {
std::cout << x;
}
int main() {
int x = 4;
f(x);
g(x);
return 0;
}
While the call to f() is fine, the call to g() gives a compile-time error. 虽然对f()的调用很好,但对g()的调用却给出了编译时错误。 Does this kind of binding work only for templates? 这种绑定仅适用于模板吗? Why? 为什么? Can we somehow do it without templates? 没有模板,我们能以某种方式做到吗?
Since T
is a template argument, T&&
becomes a forwarding-reference . 由于T
是模板参数,因此T&&
成为转发引用 。 Due to reference collapsing rules, f(T& &&)
becomes f(T&)
for lvalues and f(T &&)
becomes f(T&&)
for rvalues. 由于参考塌陷规则, f(T& &&)
变为f(T&)
为左值和f(T &&)
变为f(T&&)
为右值。
0x499602D2 has already answered your question ; 0x499602D2已经回答了您的问题 ; nevertheless, the following changes to your code might give further insights. 但是,对代码的以下更改可能会提供进一步的见解。
I have added a static_assert
to f
to check the deduced type: 我在f
添加了一个static_assert
来检查推导的类型:
#include <type_traits>
template<typename T>
void f(T&& x) {
static_assert(std::is_same<T&&, int&>::value,"");
std::cout << x;
}
The assert does not fail, so the type of x
in f
is eventually int&
(in this particular example). 断言不会失败,所以类型x
在f
是最终int&
在此特定示例中)。
I have changed how g
is called in main
: 我已经更改了main
g
的调用方式:
g(std::move(x));
Now the code compiles and the program works as expected and prints 44
. 现在,代码已编译,程序按预期工作并打印44
。
Hope this helps a bit in understanding rvalue references. 希望这有助于理解右值引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.