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