【问题标题】:Template class assignment between different types不同类型之间的模板类分配
【发布时间】: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&amp;) 并使用它自己进行完整的 School 结构转换。

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

谢谢

【问题讨论】:

  • Coed&amp; operator=(const BoysOnly&amp; other)Coed&amp; operator=(const GirlsOnly&amp; other) 是完全相同的函数,因为 BoysOnlyGirlsOnly 是同一类型。如果你想要不同的类型,那就做那些structs,即struct BoysOnly {int value; }; struct GirlsOnly { int value; };
  • 您的代码 sn-p 中有许多拼写错误。另外,BoysOnly 应该是一个类型,它应该不同于GirslOnly。这就是minimal reproducible examplelook 的喜爱。
  • 您为Coed 定义了operator=,但coedSchool = boysSchool; 将调用Schooloperator=。现在还不清楚你真正想要做什么。还有什么是隐藏类的句柄?我会把它解释为一个你只知道声明而​​不知道定义的类。

标签: c++ templates metaprogramming


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    相关资源
    最近更新 更多