It is well know that circular dependence is a bad practice.
Suppose we have two class A
and B
. Each class need using other as an input variable of member function.
I know we can using forward declaration to avoid circular dependence, that is:
// A.h
class B;
class A
{
public:
void doWithB(B& b);
...
private:
};
// A.cpp
#include "A.h"
#include "B.h"
void A::doWithB(B& b)
{
...
}
// B.h
class A;
class B
{
public:
void doWithA(A& a);
...
private:
};
// B.cpp
#include "A.h"
#include "B.h"
void B::doWithA(A& a)
{
...
}
However, if class A
and B
is template class, so the class should be implemented in headfile. One implement is that:
//A.h
#include "B.h"
template<typename Type>
class A
{
public:
void doWithB(B<Type> &b)
{
...
}
private:
};
//B.h
#include "A.h"
template<typename Type>
class B
{
public:
void doWithA(A<Type> &a)
{
...
}
private:
};
We can see that A.h
include B.h
, and B.h
include A.h
.
At these case, how can we avoid the circular dependence?
The practical class example is Array
and LinkedList
. They are template class. I need the function that transfer Array
To LinkedList
, and transfer LinkedList
to Array
. So I face the problem.
Thanks in advance. Thanks for your time.