2017-06-13 94 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