C ++:使用模板继承类

时间:2015-02-04 19:11:48

标签: c++ templates inheritance

我知道如何通常使用模板继承类。但是当谈到嵌套的类/模板时,我没有任何线索,也无法在互联网上找到任何东西(也许是因为我不知道它的关键字)。

template <typename T>
class A;

template <class T1, class T2>
class B;

template < typename T1, class T2, class T3 >
class C2:
    public C< A<T1>, B<T2, T3> >
{};

我希望C2的定义方式与定义C的方式相同,即C2< A<T1>, B<T2, T3> >而非C2<T1, T2, T3>。但我不知道如何实现这一目标的任何语法或解决方法。

编辑:T.C。是的,我希望最终用户只能写C2< A<T1>, B<T2, T3> > foo;,不允许C2<foo, bar> foo;

1 个答案:

答案 0 :(得分:3)

这对我有用:

template <typename T>
class A {};

template <class T1, class T2>
class B {};

template < typename T1, class T2>
class C {};

// forward declare C2 but don't define it.    
template < typename T1, class T2 > class C2;

// Create the only specialization that depends on using A and B.
template < typename T1, class T2, class T3 >
class C2<A<T1>, B<T2, T3> >: public C< A<T1>, B<T2, T3> >
{};

int main()
{
   C2<A<int>, B<double, float>> c1; // OK.
                                    // This creates an instance of the
                                    // only specialization that has
                                    // been defined.

   C2<int, double> c2;              // Not OK.
                                    // The generic template class has
                                    // been forward declared but has not
                                    // not been defined.
}