In C++ Templates The Complete Guide in section 5.3 Member Templates it's written:
Note that a template assignment operator doesn't replace the default
assignment operator. For assignments of stacks of the same type, the
default assignment operator is still called.
Is this correct, because when I ran below code:
#include<iostream>
using namespace std;
template<typename T>
class Pair
{
public:
T pair1,pair2;
Pair(T i,T j):pair1(i),pair2(j){}
template<typename T1>Pair<T>& operator=(Pair<T1>&);
};
template<typename T>
template<typename T1>
Pair<T>& Pair<T>::operator=(Pair<T1>& temp)
{
this->pair1 =temp.pair1*10;//At this point
this->pair2=temp.pair2;
return *this;
}
int main()
{
Pair<int>P1(10,20);
Pair<int>P2(1,2);
P2=P1;
cout<<P2.pair1<<' '<<P2.pair2<<endl;
return 1;
}
I got answer 100 20.
It didn't give the default assignment answer.
Is that a typing mistake in C++ Templates the Complete Guide?
C++ Templates: The Complete Guide By David Vandevoorde, Nicolai M.
JosuttisPublisher : Addison Wesley
Pub Date : November 12, 2002 Pages : 552
Best Answer
The copy assignment operator is indeed implicitly declared and considered by overload resolution.
As you can see the implicitly-declared copy assignment operator for
Pair<int>
has one parameter of typePair<int> const&
- note theconst
in particular! Overload resolution favours non-const
references overconst
ones if both can be bound to the argument, [over.ics.rank]/3:The specialization of the template lacks a
const
in the reference parameter, thus it's a better match and is selected.