仅定义非平凡的复制操作

时间:2016-04-02 20:02:50

标签: c++ templates copy-assignment

我有一个模板化的类,它有许多成员变量。少数这些变量具有类的模板类型,大多数具有固定类型。

我想通过转换将类的一个实例复制到另一个实例,但如果类的类型不同,则不能使用隐式副本。因此,我需要一种分配方法。

但是,为了完成我想要的转换,必须写出所有这些复制操作是不幸的。

因此,有没有办法设置赋值运算符,以便在可能的情况下完成隐式副本?

示例代码如下:

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

1 个答案:

答案 0 :(得分:1)

有两种天真的方式:

  • 创建一个复制可复制值的函数CopyFrom(const MyClass&amp; o) 然后根据您的需要从operator = overload以及最终模板专业化调用它。
  • 将所有可复制值打包在子类/结构中,您将能够使用编译器生成的默认运算符=)