[英]Rvalue reference parameters and template functions
If I define a function which accepts an rvalue reference parameter:如果我定义一个接受右值引用参数的函数:
template <typename T>
void fooT(T &&x) {}
I can call it, using GCC 4.5, with either a
, ar
, or arr
:我可以使用 GCC 4.5 使用
a
、 ar
或arr
调用它:
int a, &ar = a, &&arr = 7;
fooT(a); fooT(ar); fooT(arr);
However, calling a similar, non-template function,然而,调用一个类似的非模板函数,
void fooInt(int &&x) {}
with any of those three arguments will fail.使用这三个参数中的任何一个都会失败。 I was preparing to strengthen my knowledge of
forward
, but this has knocked me off course.我正准备加强我对
forward
了解,但这让我偏离了轨道。 Perhaps it's GCC 4.5;也许是 GCC 4.5; I was surprised to find that the first example from A Brief Introduction to Rvalue References also gives a compile error:
我惊讶地发现A Brief Introduction to Rvalue References中的第一个示例也给出了编译错误:
A a;
A&& a_ref2 = a; // an rvalue reference
The behavior of deduction in template parameters is unique, and is the reason your template version works.模板参数中的推导行为是独一无二的,这也是您的模板版本有效的原因。 I've explained exactly how this deduction works here , in the context of another question.
在另一个问题的上下文中,我已经在这里准确解释了这种推论是如何工作的。
Summarized: when the argument is an lvalue, T
is deduced to T&
, and T& &&
collapses to T&
.总结:当参数是左值时,
T
被推导出T&
,并且T& &&
折叠到T&
。 And with the parameter at T&
, it is perfectly valid to supply an lvalue T
to it.对于
T&
处的参数,向其提供左值T
是完全有效的。 Otherwise, T
remains T
, and the parameter is T&&
, which accepts rvalues arguments.否则,
T
仍然是T
,参数是T&&
,它接受右值参数。
Contrarily, int&&
is always int&&
(no template deduction rules to coerce it to something else), and can only bind to rvalues.相反,
int&&
始终是int&&
(没有模板推导规则将其强制为其他内容),并且只能绑定到右值。
In addition to GMan's correct answer A Brief Introduction to Rvalue References has an incorrect example because it was written prior to a language change which outlawed:除了 GMan 的正确答案A Brief Introduction to Rvalue References有一个不正确的例子,因为它是在禁止的语言更改之前编写的:
A a;
A&& a_ref2 = a; // an rvalue reference (DISALLOWED in C++11)
Despite this change in the language, the main uses cases described in the article (move and forward) are still explained correctly in the article.尽管语言发生了这种变化,文章中描述的主要用例(移动和前进)仍然在文章中得到了正确解释。
Update: Oh, and the same article was originally published here with (imho) slightly better formatting.更新:哦,同一篇文章最初发表在这里(恕我直言)格式稍好一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.