gpt4 book ai didi

c++ - 仅定义重要的复制操作

转载 作者:行者123 更新时间:2023-11-30 05:29:28 24 4
gpt4 key购买 nike

我有一个模板类,它有很多成员变量。这些变量中的一小部分具有类的模板类型,大多数具有固定类型。

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

但是,为了完成我想要的转换而不得不写出所有这些复制操作感觉很遗憾。

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

示例代码如下:

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

最佳答案

有两种简单的方法:

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

关于c++ - 仅定义重要的复制操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com