c++ - 不同类型之间的模板类分配
问题描述
我有一个School
使用类型 T 模板化的 struct ()。类型 T 将是用户定义的类型。其中一个类型 ( CoedSystem
) 对程序不可见,因为它被库导出为句柄。其他类型(Coed
)在程序中定义。
#include <stdlib.h>
template<typename T>
struct School
{
T var1;
T var2;
T var3;
T var4;
T var5;
T var6;
int otherData;
};
typedef unsigned int CoedSystem; //this type is like a handle to hidden class
class Coed
{
CoedSystem m_schoolSystem;
int m_yearEstablished;
public:
Coed& operator=(const CoedSystem& other)
{
this->m_schoolSystem = other;
this->m_yearEstablished = 2020;
return *this;
}
};
int main()
{
School<Coed> coedSchool;
School<CoedSystem> coedSchool2;
coedSchool2 = coedSchool;
}
问题:我怎样才能让作业 coedSchool2= coedSchool 工作。约束:我想用最少的击键来实现这一点。变量的数量School
将是两位数。类复制赋值运算符中的显式赋值操作School
将是最简单的选择,但也是最长的。有什么建议么?我正在寻找类似元编程的东西,编译器会查看Coed::operator=(const CoedSystem&)
并使用它自己进行完整的School
结构转换。
编辑了这篇文章以重新发布问题。上一个问题有很多错字,我已经在这个版本中修复了它们。
谢谢
解决方案
您需要为此提供一个模板化的复制赋值运算符School
:
template<typename T>
struct School
{
// ... members
template <typename U>
School& operator=(School<U> const & s)
{
// do copy assignment
return *this;
}
};
推荐阅读
- android - 将 android:fontFamily 传递给 Android 中的自定义视图
- firebase - 如何通过本地主机上的 Firebase Google Auth 进行身份验证
- python - 为什么我收到此错误?TypeError:“列表”对象不能解释为整数
- c - 为什么我的程序允许我更改 C 中 const char 的值?
- javascript - 即时反应上下文 api 更新状态
- angular - 更改标有 Input 装饰器的组件属性是否是一种好习惯
- php - 如何在 PHPUnit 中使用 expectException?
- hyperledger-fabric - Store Images on/off blockchain? which is better?
- mongodb - find documents for given two dates, by start_date and end_date properties in mongodb
- antd - ant design 是否有类似于 material-ui 的断点检查?