Ryan Ryan - 23 days ago 14
C++ Question

C++ ambiguous operator for template overload

I have problem with operator overloading:

I want to write a class with operator like this:

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


It's fine to call:

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


But when calling:

BigNum A,B;
A==B;


It will get the compiler error:


[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]


And there is same problem if I change

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


to

bool operator==(const BigNum &input);


But it is OK if the operator overloads are like this(but it can't do
Any type==BigNum
):

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


If I want to write the operator overload so that it can do all of these:


  • Any type == BigNum

  • BigNum == Any type

  • BigNum == BigNum



How should I fix it?Thank you.

Answer

I would suggest removing a member == template and just provide three non-member overloads for operator== - two templated, one with the BigNum on left side, another with it on the right side; and one non-templated with BigNum on both sides.

Comments