解决赋值构造函数 C++ 中的歧义

kai*_*ong 2 c++ g++ llvm ambiguous

描述

当存在某个构造函数时,我的代码不明确。但是,当我注释掉所述构造函数时,编译器会抱怨缺少必要的构造函数。

最小工作示例

struct X;

struct E{
    E(const double& r){ /* important protocol stuff */ }
    E(const X&);
};

struct X{
    X(){ /* important init stuff */ }
    ~X(){ /* important delete stuff */ }
    //X(const double& r){ *this=E(r); }  // POSITION 1
    X(const X& x){ /* important init stuff */ *this=x; }
    X(const E& e){ /* important init stuff */ *this=e; }
    const X& operator=(const X& x){ return *this=E(x); }
    const X& operator=(const E& e){ /* important stuff */ return *this; }
};

E::E(const X& x){ /* important protocol stuff */ }

E operator+(const E& x, const E& y){ /* important protocol stuff */ return E(1); }
E operator*(const E& x, const E& y){ /* important protocol stuff */ return E(2); }

int main(){
    X x,y;
    x = 3.0;
    X u = 4.0;  // POSITION 2
    y = x + u * 5.0;
    X z = 6.0 + 7.0 * y;
}
Run Code Online (Sandbox Code Playgroud)

位置 1被注释掉后,位置 2就会抛出错误。

如果包含位置 1,则存在歧义错误。

基本上,我想删除位置 1并通过 double->E->X 来投射 double->X。

问题

  1. 问题的名称是什么?
  2. 我如何解决它?

我尝试过的事情:

  • 各种构造函数前面的显式关键字。对于 E,这会导致位置 2之后 出现错误。对于 X,这会导致与注释掉位置 1相同的错误。
  • 从 X,E 的定义中删除构造函数/运算符。但这不是解决方案,因为我需要能够包含一些重要的内容
  • 尝试不同的编译器(g++ 8.3.0 和 9.2.0、clang++ 12.0.0)。这并没有改变问题。

Adr*_*ica 5

出现歧义是因为(在行中x = 3.0;)编译器无法决定使用两个赋值运算符中的哪一个:带有参数的赋值运算符X&或带有 的赋值运算符E&,因为两种参数类型都可以从给定的值转换double(因为 和E都有X构造函数带有一个const double&参数)。

您可以通过提供第三个赋值运算符来解决此错误,该运算符带有一个const double&参数,如下所示:

struct X {
    X() { /* important init stuff */ }
    ~X() { /* important delete stuff */ }
    X(const double& r){ *this=E(r); }  // Now uncommented (required)
    X(const X& x) { /* important init stuff */ *this = x; }
    X(const E& e) { /* important init stuff */ *this = e; }
    const X& operator=(const double& x) { return *this = E(x); } // Add this!
    const X& operator=(const X& x) { return *this = E(x); }
    const X& operator=(const E& e) { /* important stuff */ return *this; }
};
Run Code Online (Sandbox Code Playgroud)