1

我在标题中有这段代码(已编辑):

template <int i> class A {};
template <> class A <1> { B<1> _b; };

template <int i> class B : public A <i> {};
template <> class B <1> : public A <1> {};

并以某种方式像这样使用它:

#include "template_A_B.h"
int main ()
{
   A<1> a;
   B<1> b;
   return 0;
}

显然我得到了编译错误:

error: ‘B’ does not name a type

如果我添加 B 的前向声明

template <int i> class B;

我明白了

error: field ‘_b’ has incomplete type

编译时。

我还尝试向前声明 A 并切换类定义的顺序并得到:

error: declaration of ‘struct A<1>’
4

1 回答 1

2

在您最初的问题表述中,您只需将您的专业放在您的前向声明之后。然后一切都会正确解决。

template <int i> class A;
template <int i> class B;

template <> class A <1> {};
template <> class B <1> : public A <1> {};

template <int i> class A { B<1> _b; };
template <int i> class B : public A <i> {};

在您修改后的问题中,您创建了一个试图包含自身的结构,即使使用非模板类型也是不允许的。例如,您不能定义:

struct A { B b; };
struct B : public A {};

但是,如果您更改A为使用对B.

struct B;

struct A { B *b; };
struct B : public A {};
于 2012-06-29T08:41:00.363 回答