1
votes

Having

Bar.h

template<class T>
class Bar<T> {
//...
}

Foo.h

template<T>
class Bar<T>;
//#include "Bar.h" removed due of circular dependencies, I include it in .cpp file

template<class T>
class Foo {
...
private:
    Bar<T> *_bar;
}

As you can see, I need to include bar.h but I can't do it on my project for circual dependencies reasons..

So as I usually do, I just write definition in .h and implementation in .cpp But I have some issues with this example, because I don't know the syntax for class with template..

Is there any syntax for this? I'm getting the following compiler error with the current example:

Bar is not a class template

2
Class templates need to be fully present, unfortunately. Also prepare an SSCCE.Bartek Banachewicz
i have edited my question*msmn
ok so i have to re-design my app ><msmn
my both circular class dependencies are using template so I can't changes the class that uses the definition + include in .cpp :/msmn
You're defining your template incorrectly and you're forward declaring it incorrectly as well. Try template<typename T> class Bar {}; and template<typename T> class Bar; as a definition and forward declaration respectively. P.S definition of a template must be present in every translation unit.101010

2 Answers

0
votes

Forward declaration syntax is

template<T> class Bar;

So your code becomes:

Foo.h

template<T> class Bar;

template<class T>
class Foo {
...
private:
    Bar<T> *_bar;
};

#include "Foo.inl"

Foo.inl

#include "bar.h"

// Foo implementation ...

Bar.h

template<class T>
class Bar<T> {
//...
};
0
votes

Your example doesn't have a circular dependency. Bar doesn't depend on Foo in any way. You can do define the templates in the following order:

template<class T> class Bar {};

template<class T>
class Foo {
private:
    Bar<T> *_bar;
};

If you wish to separate the definitions into two files, you can achieve the above ordering like this:

// bar:
template<class T>
class Bar {};

// foo:
#include "bar"

template<class T>
class Foo {
private:
    Bar<T> *_bar;
};