1

多くのメンバー変数を持つテンプレート化されたクラスがあります。これらの変数の少数はクラスのテンプレート型を持ち、大多数は固定型を持ちます。

クラスのインスタンス間で変換を使用して別のインスタンスにコピーしたいのですが、クラスが同じ型を持たない場合、暗黙的なコピーを使用してコピーすることはできません。したがって、割り当て方法が必要です。

ただし、必要な変換を行うためだけに、これらの多くのコピー操作をすべて書き出さなければならないのは残念です。

したがって、可能な場合に暗黙的なコピーが行われるように代入演算子を設定する方法はありますか?

コード例は次のとおりです。

#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;
}
4

1 に答える 1