For the following class template, if you want to achieve class assignment, use the assign () function. as follows
template<class T> class MyClass{ private: T value; public: void setValue(T& _value){ value = _value; } void assign(const MyClass<T> &x){ value = x.value; } T getValue(){ return value; } }; int main(void) { MyClass<double> d; MyClass<double> dd; double temp=23.123; d.setValue(temp); dd.assign(d); cout << d.getValue() << endl << dd.getValue() << endl; return 0; }
If two classes T is not the same, then use assign () method assignment
int main(void) { MyClass<double> d; MyClass<int> i; double temp=23.123; d.setValue(temp); i.assign(d); cout << d.getValue() << endl << i.getValue() << endl; return 0; }
Questions are as follows
You can see, assign () function is the desire to target a const MyClass <int> type as an argument, but got a MyClass <double> object. Meanwhile MyClass <double> can not be converted into const MyClass <int>, then the compiler will report an error.
We need to redefine what MyClass assign the function, so that the above assignment do the same.
Template < class X-> // Add X- void ASSIGN ( const MyClass <X-> & x) {// the assignment x to be defined as another type of X- value = x.getValue (); }
Thus, the above assignment can work.
As long as from X to T assignment can be performed, then this assign function can be performed. In fact, this is to avoid having to assign a function to make parameter T must assign the object belongs to T same.