用于模板重载的 C++ 模糊运算符

标签 c++ templates operator-overloading

我对运算符重载有疑问:
我想用这样的运算符编写一个类:

class BigNum
{
    public:
        template<class T>
        bool operator==(const T &input);
        template<class T>
        friend bool operator==(const T &A,BigNum & B);
};

可以调用:

BigNum A;
int a;
A==a;
a==A;

但是调用时:

BigNum A,B;
A==B;

它会得到编译错误:

[Error] ambiguous overload for 'operator==' (operand types are 'BigNum' and 'BigNum')
[Note] bool BigNum::operator==(const T&) [with T = BigNum]
[Note] bool operator==(const T&, BigNum&) [with T = BigNum]

如果我改变也有同样的问题

template<class T>
bool operator==(const T &input);

bool operator==(const BigNum &input);

但是如果运算符重载是这样的就可以了(但它不能做Any type==BigNum):

class BigNum
{
    public:
        bool operator==(const BigNum &input);
        template<class T>
        bool operator==(const T &input);
};

如果我想编写运算符重载以便它可以完成所有这些操作:

  • 任何类型 == BigNum
  • BigNum == 任何类型
  • BigNum == BigNum

我该如何解决?谢谢。

最佳答案

我建议删除一个成员 == 模板,只为 operator== 提供三个非成员重载 - 两个模板化,一个带有 BigNum 在左侧,另一个在右侧;和一个非模板化的 BigNum 两边。

关于用于模板重载的 C++ 模糊运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40531502/

相关文章:

c++ - 如何将数字添加到字符串?

c++ - 为什么 Visual Studio 会生成这些附加文件?

c++ - 如何一起使用 C++ 和 C 可变参数?

c++ - 在链表程序中使用模板时在 C++ 中重载 << 运算符

c++ - 我如何重载下标运算符以进行交换

c++ - 在通过构造函数传递变量的对象中创建对象

c++ - 什么是信号和插槽?

templates - 我如何为 Joomla 模块使用多个模板文件

c++运算符在模板类中重载

C#,多个 == 运算符重载,没有模糊的 null 检查