【发布时间】:2021-01-03 23:47:34
【问题描述】:
我有一个使用类型 T 模板化的结构 (School)。类型 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 结构转换。
编辑了这篇文章以重新发布问题。上一个问题有很多错字,我已经在这个版本中修正了它们。
谢谢
【问题讨论】:
-
Coed& operator=(const BoysOnly& other)和Coed& operator=(const GirlsOnly& other)是完全相同的函数,因为BoysOnly和GirlsOnly是同一类型。如果你想要不同的类型,那就做那些structs,即struct BoysOnly {int value; }; struct GirlsOnly { int value; }; -
您的代码 sn-p 中有许多拼写错误。另外,
BoysOnly应该是一个类型,它应该不同于GirslOnly。这就是minimal reproducible example 对look 的喜爱。 -
您为
Coed定义了operator=,但coedSchool = boysSchool;将调用School的operator=。现在还不清楚你真正想要做什么。还有什么是隐藏类的句柄?我会把它解释为一个你只知道声明而不知道定义的类。
标签: c++ templates metaprogramming