gpt4 book ai didi

c++ - 错误 : ambiguous overload for ‘operator==’

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:28 27 4
gpt4 key购买 nike

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

但我真正想要的是解释为什么比较 enum 仅当它在 class 中完成时才会导致歧义。我编写了这个小型枚举包装器,因为我需要在我的代码中只使用 C++03。

最佳答案

调用是不明确的,因为 Enum::Typeint 版本在单个隐式转换中都是有效的,前者使用 operator Type 转换,后者使用 operator T 模板转换运算符。

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

如果你使用的是 C++11,你应该使用 scoped enums相反。

关于c++ - 错误 : ambiguous overload for ‘operator==’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34174206/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com