1

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.

Xu Hui
  • 1,213
  • 1
  • 11
  • 24
  • Please take your shown code closer to what you are trying. Surely you can make one of the two classes a template class? – Yunnosch Sep 08 '19 at 09:10
  • I modify the code. Yes. I mean two template class. template class A and template class B. – Xu Hui Sep 08 '19 at 09:22
  • 2
    There is nothing wrong with circular dependence. Related: [How to declare/define interdependent templates in C++?](https://stackoverflow.com/questions/45402913/how-to-declare-define-interdependent-templates-in-c/45403262) – user7860670 Sep 08 '19 at 09:58
  • Quick question, is it possible to use the typical STL approach of taking generic ranges instead of specific container types? – Justin Time - Reinstate Monica Sep 08 '19 at 19:31

0 Answers0