steffen
steffen

Reputation: 8968

Derived and specialised template classes that contain each other

I have this code inside a header (edited):

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> {};

And somehow use it like this:

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

Obviously I get the compilation error:

error: ‘B’ does not name a type

If I add a forward declaration of B like

template <int i> class B;

I get

error: field ‘_b’ has incomplete type

when compiling.

I also tried forward declaring A and switching the order of the class definitions and get:

error: declaration of ‘struct A<1>’

Upvotes: 1

Views: 106

Answers (1)

jxh
jxh

Reputation: 70472

In your original formulation of your question, you simply needed to put your specializations after your forward declarations. Then everything will be resolved correctly.

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> {};

In your revised question, you have created a structure that is trying to contain itself, which isn't allowed even with non-template types. For example, you are not allowed to define:

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

However, you can perform something close to what you want if you change A to use an indirect reference to B.

struct B;

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

Upvotes: 2

Related Questions