使用继承的类模板

时间:2018-02-04 17:18:43

标签: c++ templates inheritance

在以下摘录中,如何访问继承的Sub类模板?

据我所知,下面的星座问题是基类Base本身就是一个依赖类。使用typename / template访问它有效但如果经常需要Sub则很麻烦。

template<int B>
struct Base {
    template<int S>
    class Sub { };
};

template<int C>
struct Class: public Base<C> {
    // (1) Error: 'Sub' does not name a type
    using S2 = Sub<2>;

    // (2) Error: 'Base' used without template argument list
    using S3 = Base::Sub<3>;

    // (3) Error: 'Class' is incomplete here
    using S4 = Class::Sub<4>

    // (4) Works, but complicated
    using S1 = typename Class::template Sub<1>;
};

using Class0 = Class<0>;
int main() { }

Fruther警告:

  • 有没有办法在没有的情况下引用Sub 来复制Base的专业化?即,考虑Base具有多个/复杂的模板参数。这基本上是为什么选项#3不起作用以及为什么我选择Class作为选项#4中的资格。

1 个答案:

答案 0 :(得分:0)

如果您需要模板 Sub,那么您可以使用选项5,别名模板:

template<int I>
using Sub = typename Base<C>::template Sub<I>;

现在Sub在非限定名称查找期间在Class内找到,并且已知是模板。当引用特化时,它也将完全适用于从基类成员模板获得的相同类型。

See it live