I confronted different issues when overloading the addition operator of a template class.
I finally found a solution and the codes below can work without any issue.
template<class T>
class A;
template<class T>
A<T> operator + (const A<T>& , const A<T>&);
template <class T>
A<T> operator+ (A<T> & a1, A<T> & a2){
//the definition of the function
}
template <class T>
class A{
friend A<T> operator +<> (const A<T>& , const A<T>& );
private: //...whatever
public: //...whatever
};
However, after I did some experiment with the codes above, I'm very confused.
I change the friend function declaration in class A
fromfriend A<T> operator +<> (const A<T>& , const A<T>& );
tofriend A<T> operator + (const A<T>& , const A<T>& );
(the<>
after theoperator +
is deleted)
Then the codes can run and give a result, but I get a warning:warning: friend declaration 'A<T> operator+(const A<T>&, const A<T>&)' declares a non-template function
Without making the modification in step 1, I delete the template declaration of the addition operator overloading function. So the code below is deleted:
template<class T> A<T> operator + (const A<T>& , const A<T>&);
Then I got an error:error: template-id 'operator+<>' for 'A<int> operator+(const A<int>&, const A<int>&)' does not match any template declaration
I make both modifications in step 1 and step 2, then get the same warning in step 1:
warning: friend declaration 'A<T> operator+(const A<T>&, const A<T>&)' declares a non-template function
I'm confused by the issues caused by those modifications.
- What's the effect of the
<>
afteroperator +
? (see the first modification) - What's the effect of deleting the template declaration of the addition operator overloading function? (see the second modification)
- Why the code can't run and returns an error when I only make the second modification, while it can run and returns a warning when I make both the first and second modification?
Thanks in advance!