【问题标题】:Ambiguous call with overloaded r-value reference function [duplicate]具有重载 r 值引用函数的模糊调用 [重复]
【发布时间】:2015-04-26 09:15:07
【问题描述】:

我有一个带有以下声明的类:

class IcoSphere
{
[...]
private:
    int _addVertex(const glm::vec3 &p);
    int addVertex(glm::vec3 p);
    int addVertex(const glm::vec3 &&p);
[...]
};

然后,我像这样调用“addVertex”:

IcoSphere sphere;
double t = (1.0 +sqrt(5.0)) /2.0;
sphere.addVertex(glm::vec3(-1,t,0));

'addVertex' 的参数显然不是引用,但 g++ 编译器会抛出以下错误:

./network/icosphere.cpp: In static member function ‘static void IcoSphere::Create(glm::vec3&, float, std::vector<glm::tvec3<float, (glm::precision)0u> >&, int)’:
./network/icosphere.cpp:46:36: error: call of overloaded ‘addVertex(glm::vec3)’ is ambiguous
  sphere.addVertex(glm::vec3(-1,t,0));
                                    ^
./network/icosphere.cpp:46:36: note: candidates are:
./network/icosphere.cpp:19:5: note: int IcoSphere::addVertex(glm::vec3)
 int IcoSphere::addVertex(glm::vec3 p) {_addVertex(p);}
     ^
./network/icosphere.cpp:20:5: note: int IcoSphere::addVertex(const vec3&&)
 int IcoSphere::addVertex(const glm::vec3 &&p) {_addVertex(p);}
     ^

这对我来说没有多大意义,为什么认为这是一个模棱两可的电话?

【问题讨论】:

  • 大多数情况下,重载解析无法区分值传递和引用传递。您希望通过 const rvalue-ref 重载实现什么目标?
  • 我希望它尽可能使用引用重载,以消除复制对象的开销。但是,为了方便起见,我也希望可以直接传递一个值。

标签: c++ c++11 g++ ubuntu-14.04 rvalue-reference


【解决方案1】:

编译器在处理函数重载解析时,首先获取所有可行的函数,然后对它们进行排序,然后调用排序最高的函数。

例如

type var;
void func(type);
void func(tpye&&);
func(var);

这两个 func 方法的排名相同。它们都是完全匹配的。不需要提升或隐式类型转换或其他任何东西。你的问题也是同样的情况。 所以你可能想改变

int addVertex(glm::vec3 p);

int addVertex(const glm::vec3& p);

因为你不打算改变它。更多关于重载解析和右值引用重载解析,http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htmhttp://yapb-soc.blogspot.com/2015/01/rvalue-references-and-function.html

【讨论】:

    猜你喜欢
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2011-12-12
    • 2014-09-05
    • 1970-01-01
    相关资源
    最近更新 更多