Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overload operator= inside template class

Tags:

c++

templates

template<typename T> ClassA
{
    ...
    ClassA& operator=(const ClassA&);

    ...
};

// case one:
template<typename T>
ClassA<T>& ClassA<T>::operator=(const ClassA &rhs)
{ ... }

// case two:
template<typename T>
ClassA<T>& ClassA<T>::operator=(const ClassA<T> &rhs)
{ ... }

I assume case one is correct.

Question> Why we don't have to use ClassA<T> in the function parameter list such as in case two?

like image 863
q0987 Avatar asked Nov 05 '22 16:11

q0987


1 Answers

As you have seen, either version will work.

Once we have passed the ClassA<T>:: part of ClassA<T>& ClassA<T>::operator=(const ClassA& rhs) it behaves as if we were inside the class. For example, the operator can access all the members of the class.

You do have to specify the full name for the return value, because at that point we still don't know that this is a member function (or operator).

like image 60
Bo Persson Avatar answered Nov 09 '22 15:11

Bo Persson