1

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;
}
Richard
  • 56,349
  • 34
  • 180
  • 251

1 Answers1

1

There are 2 naïve ways:

  • Create a function CopyFrom(const MyClass& o) that copy the copiable values then you call it from the operator= overload plus eventually template specialization depending on your needs.
  • Pack all the copiable values in a subclass/struct, you'll be able to use the default operator= generated by your compiler ;)
Seb Maire
  • 132
  • 8