使用模板 class 作为模板参数

Using a template class as a template argument

考虑以下代码:

template <class MyB>
struct A {
    MyB *b_;
};

template <template <class> class MyA>
struct B {
    MyA<B> *a_; // How come B can be used as a complete type here?
};

评论说出了我的疑问:B是模板,怎么能在MyA<B>中作为完整类型使用呢?

template 声明的范围内,模板的名称单独指定一个完整的类型,对于每个自动生成的专业化,与该专业化同义。考虑,例如,

template<class A> struct B {
    B();
    B &operator=(B const &);
    typedef B This;
};

B 成为一个完整的类型,当有人开始使用 B.

的特定模板实例时

请记住,在创建实例之前,模板代码不会"compiled"。

在 class 模板 X 的实例化中,名称 X 可用于指代模板或模板的当前实例化。

来自[temp.local]

1 - Like normal (non-template) classes, class templates have an injected-class-name (Clause 9). The injected-class-name can be used as a template-name or a type-name.

How come B can be used as a complete type here?

B不一定是完整的时间你声明一个MyA<B>.

类型的指针

您可以使用:

template <typename T> struct Foo { T* ptr;};
struct Bar;
Foo<Bar>* ptr = nullptr;

您甚至可以使用:

template <typename T> struct Foo { T* ptr;};
struct Bar;
Foo<Bar> obj;

因为 Foo 不依赖于 Bar 在它自己的定义中的定义。