error: ambiguous overload for ‘operator==’

error: ambiguous overload for ‘operator==’

我想了解为什么我的 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 
  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;
}

编译导致:

$ 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>

我知道我可以通过提供明确的 operator==:

来解决问题
  bool operator==(Enum const &rhs) { return t_ == rhs.t_; }

但我真正要寻找的是解释为什么只有在 class 中比较 enum 才会导致歧义。我写了这个小枚举包装器,因为我需要在我的代码中只使用 C++03。

enum可以隐式转换为int(据我了解这是由于向后兼容C造成的。如果你可以使用C++11你可以使用 enum class 解决此问题,因为作用域枚举不允许隐式转换为 int.

调用不明确,因为 Enum::Typeint 版本都有效,只有一个隐式转换,前者使用 operator Type 转换,后者使用 operator T 模板转换运算符.

不清楚为什么要转换为任何类型,但如果删除该运算符,代码 works.

如果您使用的是 C++11,则应改用 scoped enums

Enum 是实现定义的整数类型,主要是 int。现在,无论您为 enum 实现什么运算符,就像您为类型 int 实现运算符一样。并且不允许为整数类型重新定义 any 运算符,例如 intdoublechar ...,因为它会改变编程语言本身的基本含义。