首页 > 解决方案 > 不同类型之间的模板类分配

问题描述

我有一个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结构转换。

编辑了这篇文章以重新发布问题。上一个问题有很多错字,我已经在这个版本中修复了它们。

谢谢

标签: c++templatesmetaprogramming

解决方案


您需要为此提供一个模板化的复制赋值运算符School

template<typename T>
struct School
{
    // ... members
    
    template <typename U>
    School& operator=(School<U> const & s) 
    { 
        // do copy assignment
        return *this; 
    }
};

推荐阅读