如何声明模板类的模板

how to declare template of template class

本文关键字:声明 何声明      更新时间:2023-10-16

如何声明模板类的模板?? 请参阅下面的代码:

File: A.h
class A
{
    ...
    ...
};
File: B.h
template <typename U>
class B
{
    ...
    ...
};
File C.h
template <class T>
class C
{
    ...
    ...
};
File C.cpp
//In this file I am able to write template declaration for class A(non-template class)
#include "A.h"
template C<A>; //this works fine. 
How can I write the same for class B(which is a template class.)
#include "B.h"
template C<What should I write here for class B?>;
如果你想

使用B作为C类模板的类型参数,那么你可以这样写:

template class C<B<int> >; //i.e provide the some type B template class
       //^^^^ this is needed for explicit instantiation!
C<B<A> >  variable;
C<B<short> >  *pointer = new C<B<short> >();

C模板需要非模板类型,以便它可以生成类。这就是为什么C<A>有效:A不是模板。但是,C<B>不起作用,因为B只是类型本身的模板。您需要具有某种类型来实例化B模板。

例如,这可以工作:

C<B<A> > x;

你可以这样写:

C< B< A > > c;

如果你觉得这令人困惑,那么你可以使用typedef:

typedef B<A> MyB;
C<MyB> c;

好吧,B 也是一个模板,所以像 C<B<A>> 这样的东西会起作用。

请注意,某些编译器将 >> 视为移位运算符,并且需要 C<B<A> >