右值参考模板推导
template<class U>
void f( U && v)
{
std::cout << typeid(v).name() << "\n"; //'int' in both cases
if( boost::is_same<int&&,U>::value )
{
std::cout << "reach here\n"; //only with f<int&&>(int(1));
}
}
int main()
{
f(int(1));
f<int&&>(int(1));
std::cin.ignore();
}
当我没有显式使用 f
时,为什么 v 参数被解释为 int
? 有什么区别? (用 MVS2010 编译)
我的猜测是 First 作为右值传递,第二个作为右值引用传递,并且两者都正确绑定到右值引用中,对吗?
谢谢。
template<class U>
void f( U && v)
{
std::cout << typeid(v).name() << "\n"; //'int' in both cases
if( boost::is_same<int&&,U>::value )
{
std::cout << "reach here\n"; //only with f<int&&>(int(1));
}
}
int main()
{
f(int(1));
f<int&&>(int(1));
std::cin.ignore();
}
Why v parameter is interpreted as int
when I don't explicitly use f<int&&>
?
What is the difference ? (Compiled with MVS2010)
My guess is that First is passed as a rvalue and second as a rvalue reference and both bound correctly into a rvalue reference, am I right ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个变体
第二个变体
像这样
First variant
Second variant
Like this
不,不是真的。永远不会推导出右值引用。概念
U&&
(其中U
是可推导的模板参数)用于指示应该推导U
,使得参数被保留:X
类型的右值时,U
的类型变为X
。X
类型的 cv 限定左值时,U
变为类型X cv&
。更有趣的问题是在第二次调用中显式指定的右值引用发生了什么,因为没有进行任何推导,因为在这种情况下,两个右值引用被折叠为一个。
No, not really. An rvalue reference is never deduced. The notion
U&&
withU
being a deducible template parameter is used to indicate thatU
should be deduced such that the rvalue-ness of the argument is retained:X
the type ofU
becomesX
.X
thenU
becomes the typeX cv&
.The more interesting question is what happened to the rvalue references explicitly specified in the second call because there is no deduction going on because in this case the two rvalue references are collapsed into just one.