c++ - 在 G++ 中访问相等比较运算符时出现歧义错误

标签 c++ g++ language-lawyer multiple-inheritance comparison-operators

在多重继承的情况下,如果所有父类都有自己的相等比较operator ==,并且子类有一个(友元)函数operator ==,如下在示例中:

struct A {
    bool operator ==(const A&) const = default;
};

struct B {
    bool operator ==(const B&) const = default;
};

struct C : A, B {};

constexpr bool operator ==(const C&, const C&) { return true; }

static_assert( C{} == C{} );

GCC 在尝试比较子对象时打印以下有关歧义的错误:

 error: request for member 'operator==' is ambiguous
   13 | static_assert( C{} == C{} );
 note: candidates are: 'bool B::operator==(const B&) const'
 note:                 'bool A::operator==(const A&) const'

演示:https://gcc.godbolt.org/z/W3qer376d

这个错误看起来令人惊讶,因为 operator ==(const C&, const C&) 应优先作为最适合实际参数的操作符。这只是 GCC 的一个缺陷吗?

最佳答案

事实上,全局运算符operator==(const C&, const C&)具有优先权。然而,编译器“想知道”所有可能性以便做出决定:换句话说:一旦您尝试使用operator==,编译器就会要求您没有歧义,即使所需的替代方案不在模棱两可的替代方案之间。


struct C : A, B { using A::operator==; }; 

这解决了歧义并允许您使用全局operator==

https://onlinegdb.com/nxMjPN4NC

#include <iostream>

struct A {
    bool operator ==(const A&) const { std::cout << "A" << std::endl; return true; };
};

struct B {
    bool operator ==(const B&) const { std::cout << "B" << std::endl; return true; };
};

struct C : A, B 
{
    //using A::operator==; // Uncomment this to make it work.
};

bool operator ==(const C&, const C&) { std::cout << "C" << std::endl; return true; }

int main()
{
    C c1, c2;
    
    c1==c2;

    return 0;
}

结果(解决后):

C

关于c++ - 在 G++ 中访问相等比较运算符时出现歧义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69401732/

相关文章:

c++ - C++ 中的 cstdint 未定义 uint_t 系列

c++ - 非静态非引用数据成员声明变量吗?

c++ - undefined symbol ,尽管它们在我们的 .cpp 文件中定义

c++ - 解析 XML 文件以填充 C/C++ 中的结构

c++ - 如果 MinGW 不是一个非常可行的选项,则需要有关使用 MinGW 或任何其他 C++ 编译器编译 Direct Sound 的帮助

c++ - 为什么写入文件会大大增加缓存未命中和分支未命中?

c++ - 具有两个不同缓冲区的指针算法

c++ - 删除复制构造函数时,为什么重载决议不会返回到引用基类的构造函数?

c++ - 从 C++ 文件中读取特定行

c++ - 删除文件的开头而不重写整个文件