c++ - 为什么 == 运算符重载枚举在 MSVC 中不明确

标签 c++ c++11 visual-c++ enums operator-overloading

除了 MSVC,以下代码在我检查过的所有编译器(clang、mingw、g++)上都能正常编译。

enum class Foo{BAR};

bool operator==(Foo a, Foo b)
{
    return (int)a & (int)b;
}

int main(int argc, char *argv[])
{
    Foo::BAR==Foo::BAR;
    return 0;
}

MSVC 失败并出现以下错误:

>main.cpp(10): error C2593: 'operator ==' is ambiguous
>main.cpp(3): note: could be 'bool operator ==(Foo,Foo)'
>main.cpp(10): note: while trying to match the argument list '(Foo, Foo)'

任何见解都会很棒,我整天都在为这个问题挠头。

我的 MSVC 版本是 14.0,但是我用版本 19.00.23506 在线测试了它,但出现了同样的错误。

但是 19.11.25331.0 版本没有出现该错误。 那么编译器错误?

最佳答案

对于枚举,有一个内置的比较运算符。当您定义自己的时,内置应该会自动隐藏。

[over.built/1]

The candidate operator functions that represent the built-in operators defined in Clause [expr] are specified in this subclause. These candidate functions participate in the operator overload resolution process as described in [over.match.oper] and are used for no other purpose. [ Note: Because built-in operators take only operands with non-class type, and operator overload resolution occurs only when an operand expression originally has class or enumeration type, operator overload resolution can resolve to a built-in operator only when an operand has a class type that has a user-defined conversion to a non-class type appropriate for the operator, or when an operand has an enumeration type that can be converted to a type appropriate for the operator. Also note that some of the candidate operator functions given in this subclause are more permissive than the built-in operators themselves. As described in [over.match.oper], after a built-in operator is selected by overload resolution the expression is subject to the requirements for the built-in operator given in Clause [expr], and therefore to any additional semantic constraints given there. If there is a user-written candidate with the same name and parameter types as a built-in candidate operator function, the built-in operator function is hidden and is not included in the set of candidate functions. — end note ]

回答你的问题,是的,这似乎是一个编译器错误。

关于c++ - 为什么 == 运算符重载枚举在 MSVC 中不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44515148/

相关文章:

c++ - 请求 Y 的非类类型 Z 的成员 X

c++ - 返回不可变的新实例的正确方法是什么?

c++ - 通过 system() 调用启动另一个程序会阻塞套接字

c++ - 如何让一个 C++11 线程运行多个不同的函数?

c++ - std::numeric_limits<double>::min() 上的错误 C2589

c++ - 如何使用 C 预处理器将连接的字符串转换为宽字符?

c++ - 使用模板打印一个类

c++ - 在 C++11 中从 C++17 重新实现 std::map::try_emplace()?

c++ - 缩小从 `int`(常量表达式)到 `unsigned int` 的转换 - MSVC vs gcc vs clang

c++ - 模板特化在链接时失败