【问题标题】:Implicit operator != resolving ambiguity in operators ==隐式运算符 != 解决运算符中的歧义 ==
【发布时间】:2021-11-14 20:11:06
【问题描述】:

如果某个结构体A已经显式声明了operator ==方法,但同时有一个全局的operator ==接受A类型的参数,那么相等比较会导致歧义错误。

在 C++20 中,我们可以调用不等式 operator !=,编译器会将其解释为相等运算符的否定。我虽然在相同的情况下也会出现歧义错误,并且确实 GCC 和 Clang 显示了它,但最新的 Visual Studio 2019 接受了代码:

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

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

int main() {
    A a;
    //a == a; //error everywhere
    return a != a; //ok in MSVC
}

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

这仅仅是 MSVC 中的一个错误吗?

【问题讨论】:

  • 嗯,这很有趣。我试图在我的本地 MSVC 编译器中运行完全相同的代码,它确实做到了give me an error about the ambiguous operator overloads of operator==。我不太确定为什么它不会发生在你的情况下,但我会在这里大胆猜测并说 godbolt.org 使用的 MSVC 编译器 可能 i> 以某种方式被破坏/过时。
  • 我在 VS2019 16.10.1 上收到此错误:Error C2676 binary '!=': 'A' does not define this operator or a conversion to a type acceptable to the predefined operator ConsoleApplication3 + C。编译器设置设置为 C++17 标准。 @Ruks 你的 VS 版本和设置是什么?
  • @Jabberwocky VS2019 16.11.2 是我目前使用的版本。并且您需要使用 C++20 编译它,否则即使您删除已删除的 operator== 重载以消除歧义,此代码也不会编译。 (C++17 没有从 operator== 隐式生成 operator!=。)
  • 听起来确实像一个 MSVC 错误。
  • 我建议你可以参考线程:stackoverflow.com/questions/58319928/…

标签: c++ visual-studio language-lawyer c++20


【解决方案1】:

这似乎是 MSVC 中的一个错误,预计很快会修复: https://developercommunity.visualstudio.com/t/incorrect-acceptable-of-ambiguous-operator/1535876

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 2022-06-12
    • 2015-08-28
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2020-12-16
    相关资源
    最近更新 更多