Inhering type declarations in a hierarchy of templates

狂风中的少年 提交于 2019-12-13 06:27:19

问题


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;
};


来源:https://stackoverflow.com/questions/37206745/inhering-type-declarations-in-a-hierarchy-of-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!