右值引用参数和模板函数
如果我定义一个接受右值引用参数的函数:
template <typename T>
void fooT(T &&x) {}
我可以使用 GCC 4.5 使用 a
、ar
或 arr
来调用它:
int a, &ar = a, &&arr = 7;
fooT(a); fooT(ar); fooT(arr);
但是,使用这三个参数中的任何一个调用类似的非模板函数
void fooInt(int &&x) {}
都会失败。我正准备加强我的forward
知识,但这让我偏离了方向。也许是 GCC 4.5;我惊讶地发现 右值引用简介 中的第一个示例也给出了编译错误:
A a;
A&& a_ref2 = a; // an rvalue reference
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
:
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. Perhaps it's 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 a;
A&& a_ref2 = a; // an rvalue reference
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模板参数的推导行为是独特的,这就是您的模板版本起作用的原因。我已经在此处在另一个上下文中准确解释了此推导的工作原理问题。
总结一下:当参数是左值时,
T
被推导为T&
,并且T& &&
折叠为T&
。对于T&
处的参数,向其提供左值T
是完全有效的。否则,T
仍为T
,参数为T&&
,它接受右值参数。相反,
int&&
始终是int&&
(没有模板推导规则将其强制为其他内容),并且只能绑定到右值。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 toT&
, andT& &&
collapses toT&
. And with the parameter atT&
, it is perfectly valid to supply an lvalueT
to it. Otherwise,T
remainsT
, and the parameter isT&&
, which accepts rvalues arguments.Contrarily,
int&&
is alwaysint&&
(no template deduction rules to coerce it to something else), and can only bind to rvalues.除了 GMan 的正确答案 右值引用简介 还有一个不正确的示例,因为它是在禁止的语言更改之前编写:
尽管语言发生了这种更改,但文章中描述的主要用例(移动和前进)仍然在文章中得到了正确的解释。
更新:哦,同一篇文章最初发表于 这里(恕我直言)格式稍微好一些。
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:
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.