Inhering type declarations in a hierarchy of templ

2019-09-11 02:59发布

问题:

Consider this:

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.

Is there any way this can be made shorter?

A related question was asked, but did not make the point of how bad the duplication was and did not receive any replies.

回答1:

If you don't want to import or redeclare the typenames in the derived class, you need at least to tell the compiler to look up the typenames in the derived class hierarchy.

You can do this using the name of the derived class as the qualifying scope:

typename B::MyType1 x;

If B is a long name, or you want to be able freely to move code between B and C, you can conventionally add a typedef at the head of the class:

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