I have the following code:
#include <iostream>
using namespace std;
template<typename T> class myclass {
public:
T data;
myclass(T const & _data = T()) : data(_data) {}
template<typename U> myclass<T> & operator=(myclass<U> const & rhs) {
cout << data << " = " << rhs.data << endl;
return *this;
}
};
int main() {
myclass<double> first(1);
myclass<float> second(2);
myclass<double> third(3);
first=second;
first=third;
}
Now, althought it compiles perfectly, the output is only:
1 + 2
Why isn't first=third making a call to
myclass<double> & operator=(myclass<double> const & rhs)
?
The copy assignment operator is never a function template. Since the class doesn't declare a copy assignment operator the compiler generates one and uses this generated operator. If you add an operator like this, you'll see the assignment:
myclass<T>& operator= (myclass<T> const& rhs) {
std::cout << "(copy) " << data << " = " << rhs.data << '\n';
return *this;
}