Search code examples
c++templatesoperator-overloading

How to do an operator overload for a class template method


I am having trouble avoiding errors when trying to overload operators in my class's cpp file. I have tried many variations but cannot get the right syntax.

Currently I have this, which has an error "deduced class type 'TreeSet' in function return type".

// cpp file
template <typename T>
TreeSet TreeSet<T>::operator+(const TreeSet &other) {}

The function was declared as this, where the class is a template with typename T. I am also not allowed to change anything in the header file.

// header file
TreeSet operator+(const TreeSet &other);

I tried specifying the template type for the return type and/or the parameter, neither of which provided a solution.


Solution

  • The compiler cannot deduce the class type 'TreeSet' in the return type of your function, because the template parameter 'T' is missing.

    You just need to do this:

    template <typename T>
    TreeSet<T> TreeSet<T>::operator+(const TreeSet &other) {
        // Your implementation here
    }