在模板层次结构中继承类型声明

时间:2016-05-13 09:49:32

标签: c++ templates inheritance using code-duplication

考虑一下:

template <typename T>
struct A {
    using MyType1 = ...;
    using MyType2 = ...;
    using MyType3 = ...;
    using MyType4 = ...;
    using MyType5 = ...;
    ...
};

template <typename T>
struct B: A<T> {
    using MyType1 = typename A<T>::MyType1;
    using MyType2 = typename A<T>::MyType2;
    using MyType3 = typename A<T>::MyType3;
    using MyType4 = typename A<T>::MyType4;
    using MyType5 = typename A<T>::MyType5;
    ...
};

template <typename T>
struct C: A<T> {
    using MyType1 = typename A<T>::MyType1;
    using MyType2 = typename A<T>::MyType2;
    using MyType3 = typename A<T>::MyType3;
    using MyType4 = typename A<T>::MyType4;
    using MyType5 = typename A<T>::MyType5;
    ...
};

... // Many more classes in the hierarchy 
    // with all the type declarations duplicated in each of them.

有什么方法可以缩短它?

有人询问了一个相关的question,但没有说明重复有多糟糕,也没有收到任何回复。

1 个答案:

答案 0 :(得分:1)

如果您不想导入或重新声明派生类中的类型名,则至少需要告诉编译器在派生类层次结构中查找类型名。

您可以使用派生类的名称作为限定范围来执行此操作:

typename B::MyType1 x;

如果B是长名称,或者您希望能够在BC之间自由移动代码,则可以在类的开头添加typedef:

template <typename T>
struct B: A<T> {
    using ThisType = B;
    // ...
    typename ThisType::MyType1 x;
};
相关问题