-1

This code:

template <typename T>
class A {
    operator ==(const T &a, const T &b);
}

cause error:

bool Tree<T>::operator==(const T&, const T&)’ must take exactly one argument
bolov
  • 72,283
  • 15
  • 145
  • 224

2 Answers2

0

Well, there are two ways.

friend bool operator== (MyClass const & lhs, MyClass const & rhs); 

bool MyClass::operator== (MyClass const & rhs) const;

You have sort of combined them now. Use one of the above.

Either a friend function outside the class, or (as suggested by rafix07) remove the other object from the member function.

Also you might want to read this: What are the basic rules and idioms for operator overloading?

0xbaadf00d
  • 2,535
  • 2
  • 24
  • 46
0

Member operators, like any other member function, have one operand hidden. It's *this object and they access left-hand operator through this pointer. For other member functions it meant to be left-hand operand of operators -> or . (dot).

That leads to next difference between member operator and stand-alone operator: stand-alone operator can be used with left-hand operand that can be converted to the specified type. That's not possible when using a member. Either behavior might be desirable depending on semantics.

E.g. you want use operator == to check if two instances of same type are equal:

template <typename T>
class A {
    T  data;
public:  // note: this is important, if operator 
         // is not public, only this class can do comparison.
    bool operator ==(const A &b) {
        // this would invoke operator == for T class 
        return  this->data == b.data; 
    }
    // compare data with T object
    bool operator ==(const T &b) {
        return  this->data == b; 
    }
};

For template class standalone operators are problematic. They have to be templates and to be declared in way they can be used for that template. It's rarely done outside of libraries.

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42