I have a class, say A
template <typename T> class A
{
} ;
and a class derived from A<T>, (retaining type genericity)
template <typename T> class B : public A<T>
{
} ;
A situation has arisen where i need to instantiate a B<T> inside a method declared in A<T>. Uh oh.
template <typename T> class A
{
void go()
{
B<T> * newB = new B<T>() ; // oh boy, not working..
}
} ;
What should I do and how do I work around this?
You need to break the cyclic dependency between the two classes. Trivial in this case: just define your
go()function out of line:I prefer out of line definitions, even when inlining functions, anyway because it avoids cluttering the interface with unnecessary detail. I also prefer to not have cyclic dependencies (certainly not between base and derived) but it can’t always be avoided.