As per cppreference, a copy assignment operator should non templated :
A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T, T&, const T&, volatile T&, or const volatile T&"
But in this sample program, i wrote a templated assignment operator, there is no compilation issue and it infact is called(and not default implicitly generated).
template<typename T1>
class Sample
{
public:
T1 a;
Sample(T1 b)
{
a=b;
}
template<typename T2>
void operator = (T2& obj2)
{
cout<<"This wont be called";
(*this).a=obj2.a;
}
};
Sample<int> obj1(2);
Sample<int> obj2(3);
obj2=obj1;
Output:
This wont be called
Am i misunderstanding something?
template<typename T2> void operator = (T2&) is not the copy-assignment operator.
so the default one void operator = (const Sample&) is generated.
but your is a better match for:
Sample<int> obj1(2);
Sample<int> obj2(3);
obj2 = obj1;
But with
const Sample<int> obj1(2);
Sample<int> obj2(3);
obj2 = obj1;
You will have your expected result:
Demo
template<typename T2>
void operator=(T2& obj2) { ... }
defines a operator= function but it is not the copy-assignment operator as per the standard. To qualify as a copy-assignment operator, it has to be:
void operator=(Samble& obj2) { ... }
or better
Sample& operator=(Sample const& obj2) { ... }
Given your code, you may use:
Sample<int> a;
Samble<double> b;
b = a;
If you had the real copy-assignment operator, that would fail to compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With