在模板层次结构中的类型声明 [英] Inhering type declarations in a hierarchy of templates

查看:193
本文介绍了在模板层次结构中的类型声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这样:

 模板< 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;
...
};

... //在层次结构中有更多的类
//所有类型声明在每个类中都重复。有什么方法可以缩短吗?










< b

与此相关的问题被问及,但没有说明重复是多么糟糕,没有收到任何回复。

解决方案

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



您可以使用派生类的名称作为限定范围:

  typename B :: MyType1 x; 

如果 B 是长名称,您希望能够在 B C 之间自由移动代码,您可以常规地在头部添加typedef类:

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


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.

解决方案

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

这篇关于在模板层次结构中的类型声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆