I have a templated class which has many member variables. A small number of these variables have the template type of the class, the majority have fixed types.
I'd like to copy between one instance of the class to another with conversions, but cannot do so using implicit copy if the classes do not have the same type. Therefore, I need an assignment method.
However, it feels unfortunate to have to write out all of those many copy operations just to do the conversion I want.
Therefore, is there a way to set up the assignment operator such that implicit copies are done where possible?
An example code follows:
#include <iostream>
template<class T>
class MyClass {
public:
int a,b,c,d,f; //Many, many variables
T uhoh; //A single, templated variable
template<class U>
MyClass<T>& operator=(const MyClass<U>& o){
a = o.a; //Many, many copy operations which
b = o.b; //could otherwise be done implicitly
c = o.c;
d = o.d;
f = o.f;
uhoh = (T)o.uhoh; //A single converting copy
return *this;
}
};
int main(){
MyClass<int> a,b;
MyClass<float> c;
a.uhoh = 3;
b = a; //This could be done implicitly
std::cout<<b.uhoh<<std::endl;
c = a; //This cannot be done implicitly
std::cout<<c.uhoh<<std::endl;
}