rvalue reference template deduction

我的梦境 提交于 2019-12-09 18:41:10

问题


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.


回答1:


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.




回答2:


First variant

f(int(1)) <=> f<int>(int(1)) <=> U==int <=> is_same<int&&,int> == false

Second variant

f<int&&>(int(1)) <=> U==int&& is_same<int&&,int&&> == true

Like this



来源:https://stackoverflow.com/questions/8842312/rvalue-reference-template-deduction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!