Error: ambiguous overload for 'operator ==

I am trying to understand why my C ++ compiler is confused with the following code fragment:

struct Enum { enum Type { T1, T2 }; Enum( Type t ):t_(t){} operator Type () const { return t_; } private: Type t_; // prevent automatic conversion for any other built-in types such as bool, int, etc template<typename T> operator T () const; }; enum Type2 { T1, T2 }; int main() { bool b; Type2 e1 = T1; Type2 e2 = T2; b = e1 == e2; Enum t1 = Enum::T1; Enum t2 = Enum::T2; b = t1 == t2; return 0; } 

The selection leads to:

 $ c++ enum.cxx enum.cxx: In function 'int main()': enum.cxx:30:10: error: ambiguous overload for 'operator==' (operand types are 'Enum' and 'Enum') b = t1 == t2; ^ enum.cxx:30:10: note: candidates are: enum.cxx:30:10: note: operator==(Enum::Type, Enum::Type) <built-in> enum.cxx:30:10: note: operator==(int, int) <built-in> 

I understand that I can solve the symptoms by providing an explicit operator== :

  bool operator==(Enum const &rhs) { return t_ == rhs.t_; } 

But in fact, what I'm looking for is an interpretation of why enum comparisons only lead to ambiguity when they are executed within the class . I wrote this little enum wrapper since I only need to use C ++ 03 in my code.

+5
source share
3 answers

The call is ambiguous, since the Enum::Type and int versions are valid with one implicit conversion, the first using an operator Type conversion, and the second using an operator T template conversion operator T .

It is not clear why you have conversion to any type, but if you delete this statement, the code works .

If you are using C ++ 11, you should use copied enums instead .

+2
source

enum can be implicitly converted to int (as far as I understand, this is caused by backward compatibility with C If you can use C++11 , you can use the enum class to solve this problem, since the scope of the enum does not allow implicit conversion to int .

0
source

Enum is a specific integral type of implementation that is basically int . Now, any operator that you implement for Enum is like you are executing an operator for type int . And overriding any operator for integral types, such as int , double , char ... is not allowed, as it will change the main meaning of the programming language itself.

0
source

Source: https://habr.com/ru/post/1237732/


All Articles