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

1

有两种天真的方法:

  • 创建一个复制可复制值的函数 CopyFrom(const MyClass& o),然后根据您的需要从 operator= 重载加上最终的模板专业化调用它。
  • 将所有可复制的值打包在子类/结构中,您将能够使用编译器生成的默认 operator= ;)
于 2016-04-02T21:15:27.670 回答