rvalue参数引起的多种实现 [英] Multiple implementation caused by rvalue parameter

查看:80
本文介绍了rvalue参数引起的多种实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的测试代码:

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;
}

当我尝试调用test(std::move(v))时,被告知test是乘法实现的.显然,我使用过std :: move使v成为右值. test(std::vector<int> &&)不会被专门称为吗?

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?

推荐答案

这与右值或移动没有直接关系.左值引用重载也会发生同样的情况

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;
}

两个重载的隐式转换序列是等效的.您的示例仅在移动时突然出现的原因是,第一个调用传递了一个左值(使第二个重载不适用),而再次应用std::move会产生两个等效的转换序列.

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.

这篇关于rvalue参数引起的多种实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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