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

标签 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被问到,但没有说明重复有多糟糕,也没有收到任何回复。

最佳答案

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

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

typename B::MyType1 x;

如果 B 是一个长名字,或者你希望能够在 BC 之间自由移动代码,你可以按照惯例添加类开头的 typedef:

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

关于c++ - 在模板层次结构中继承类型声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37206745/

相关文章:

python - C++ - argsort 的 vector 版本实现与 numpy 中的相比效率低

c++ - 组合继承自的类的对象?

c++ - 注册特定文件扩展名的 Windows shell 命名空间文件夹 View 扩展名

c++ - const_cast : override a const status

c++ - 可变参数模板和 std::array 意外行为

c++ - C++ 中的模板

python : metaclass + wrapped methods + inheritance = problems

java - 从父类(super class)调用子类中的重写方法

c++ - 为什么在重定向 stdout 和 stdin 时 Python 的行为不符合预期?

C++编译时检查模板类型中是否存在方法