我试图理解为什么我的c ++编译器与以下代码混淆:
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 templateoperator 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; }
编译导致:
$ 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)enum.cxx:30:10: note: operator==(int, int)
我明白我可以通过明确说明来解决症状operator==
:
bool operator==(Enum const &rhs) { return t_ == rhs.t_; }
但我真正想要的是解释为什么enum
只有当它在一个内部完成时才会导致歧义class
.我写了这个小的枚举包装,因为我只需要在我的代码中使用C++ 03.