右值引用模板扣除 [英] rvalue reference template deduction

查看:197
本文介绍了右值引用模板扣除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  template< class U> 
void f(U&& v)
{
std :: cout< typeid(v).name()< \\\
; //'int'in both cases

if(boost :: is_same {
std :: cout< ; reach here\\\
; // only with f< int&&>(int(1));
}
}


int main()
{
f(int(1));

f< int&&>(int(1));

std :: cin.ignore();
}

为什么v参数解释为 int 当我没有明确使用 f< int&&>
有什么区别? (编译MVS2010)



我的猜测是First作为右值传递,第二个作为右值引用,并且都正确地绑定到右值引用中,对吧? / p>

谢谢。

解决方案

从不推导出右值引用。作为可推导模板参数的 U&&& U 的概念用于表示应当推导U 以便保留自变量的右值:




  • 类型 X U 的类型变为 X 传递类型为 X cv 限定lvalue的

  • $ c>成为 X cv& 类型。



是在第二次调用中显式指定的右值引用发生了什么,因为没有扣除,因为在这种情况下,两个右值引用被折叠成一个。


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.

解决方案

No, not really. An rvalue reference is never deduced. The notion U&& with U being a deducible template parameter is used to indicate that U should be deduced such that the rvalue-ness of the argument is retained:

  • when passing an rvalue of type X the type of U becomes X.
  • when passing a cv qualified lvalue of type X then U becomes the type X 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.

这篇关于右值引用模板扣除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆