除了 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 版本没有出现该错误。 那么编译器错误?
最佳答案
对于枚举,有一个内置的比较运算符。当您定义自己的时,内置应该会自动隐藏。
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/