elelias
elelias

Reputation: 4761

template circular dependency issue

second template question of the day, what a n00b:

I have a template class:

template <class T>
class foo{
  private:
     //...
     T SubFoo;
     //...

};

I also have a class called myClass. I would like to have objects of the kind:

foo<myClass> myObject;

But, and here's the problem, I would like to be able to get a pointer to myObject from myObject.SubFoo. That means that one of the members of the class myClass should be an instantiation of the template class foo.

So I can do:

class myClass{
   //...
   foo<myClass>* point2myClass;

}

However, it seems that this does not work because

./foo.h:103: error: ‘foo::SubFoo’ has incomplete type

When defining myClass, the program finds the line

   foo<myClass>* point2myClass;

It goes to the defintion of foo and it finds:

     T SubFoo;

but T, in this case myClass, has not yet been defined (that is what the program was doing!), so it doesn't know what T is, hence the error.

If I interchange the order of declarations, it will also fail because "foo" will not be defined.

How can I make this work??

Thanks a million!

Upvotes: 1

Views: 180

Answers (1)

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36433

The following code, should definitely work just fine. If your code is different, please specify where.

template < typename T >
struct A
{
    T x;
};

struct X
{
    A<X>* x;
};

int main()
{
    X a;
}

Upvotes: 1

Related Questions