2017-06-13 67 views
7

以下代码可以编译我检查过的所有编译器(clang,mingw,g ++),而不是MSVC。为什么==运算符在MSVC中含糊不清的运算符重载

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不兼容。 编译错误呢?

+6

可能是因为有内置的。 – StoryTeller

+1

作为一个方面说明,如果我必须使用您的'operator =='版本,我会感到困惑,因为它不会测试相等性。 – piwi

+0

@piwi - 这只是重现模糊错误的最小代码, – hippiemancam

回答

7

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

[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 ]

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

+0

谢谢你,很高兴知道我不只是疯了。 – hippiemancam

+0

这并不是内置应用程序的工作方式。 –

+0

@ T.C。 - 引用了错误的段落(现在已修复),但编译器错误仍然存​​在。 – StoryTeller