Multiple implementation caused by rvalue parameter

空扰寡人 提交于 2019-12-22 18:49:58

问题


Here is my test code:

void test(std::vector<int> vec){};
void test(std::vector<int> && vec){};

int main(int argc, char * argv[])
{
    std::vector<int> v;
    test(v);
    test(std::move(v));

    return 0;
}

When I try to call test(std::move(v)), I was told test is multiply implemented. Obviously I have used std::move making v a rvalue. Won't test(std::vector<int> &&) be called specifically?


回答1:


This isn't directly related to rvalues, or moving. The same happens with an lvalue reference overload

void test(std::vector<int> vec){};
void test(std::vector<int> & vec){};

int main(int argc, char * argv[])
{
    std::vector<int> v;
    test(v); // ambiguous

    return 0;
}

The implicit conversion sequences of the two overloads are equivalent. The reason your example only flares up on a move is that the first call passes an lvalue (making the second overload not applicable), while applying std::move again produces two equivalent conversion sequences.

Accepting a parameter by value means the argument can be initialized by either a move or a copy. So if you have another overload on a reference (be it rvalue or lvalue), there is going to be an ambiguity for that value category.



来源:https://stackoverflow.com/questions/53627939/multiple-implementation-caused-by-rvalue-parameter

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