【发布时间】:2025-12-09 19:10:02
【问题描述】:
我试图理解为什么我的 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。
【问题讨论】:
-
您有一个
operator T ()使Enum可转换为 any 类型。这会引起很多歧义。
标签: c++ comparison operators