Templated Class has a circular dependency

I have two classes. One of them is the management class, which stores a bunch of working classes. Workers are actually templates.

#include "worker.h"    
class Management {

     private: 
      worker<type1> worker1;
      worker<type2> worker2;
      ...

};

The problem arises because the template classes must use Management.

Example:

class Worker{
   ...
};

#include "Worker.inl"

Working inl file:

#include "Management.h"  //Circular Dependency!

Worker::Worker(){
    //Management is accessed here
    Management mgmt1();
    mgmt1.doSomething(); //Can't use that forward declaration!
}
...

Typically, you send a Management.h declaration to the Worker header file and name it day. Unfortunately, since the template is templated, it will always be included.

I assume that you can argue that the design is bad, because the template does not have to be template if it needs to know such information, but that’s what it is and I have to work with it.

You can also consider this issue as a microcosm of office life.

+3
5

Management worker.inl(.. / Management), :

class Management;

Worker::Worker(){
    Management* mgmt1; // fine
    Management& mgmt2; // fine
    //mgmt1 = new Management(); // won't compile with forward declaration
    //mgmt2.doSomething(); // won't compile with forward declaration
}

cpp, .

, Worker , Management:

  worker<type1> worker1;

.

, , , .

+2

, . .

EDIT: , . (. CodePad)

< >    ;

class Managment
{
    worker<type1> a;
    worker<type2> b;
};

template<typename T> class worker
{
///... okay to use class Managment here.
};

#include <iostream>

class type1 {};
class type2 {};

class Managment;

template<typename T> struct worker
{
    inline void doSomethingElse();
};

class Managment
{
    worker<type1> a;
    worker<type2> b;
public:
    inline void doSomething();
};


inline void Managment::doSomething()
{
    a.doSomethingElse();
    b.doSomethingElse();
}

template<typename T>
inline void worker<T>::doSomethingElse()
{
    std::cout << "Hello!";
}

int main()
{
    Managment mgmt;
    mgmt.doSomething();
}
+1

- . , , Worker Management, :

interface IManagementOps
{
public:
    void DoStuff() = 0;
};

class Worker
{
    IManagementOps* pOps;
    ...     
};

class Management : public IManagementOps
{
    ...
};

, , , Worker, Management.

+1

, , - .

, /.

0

Management from worker class, Management . - :

template <class mngmnt, int type >
class worker{
  mngmnt* p_mngmnt;  
public:
  char* getManagementName(){return p_mngmnt->management_name;}
};


class Management {

public:
 char* management_name;

 private: 
   worker<Management,1&gt worker1;
   worker<Management,2&gt worker2;

};

0

Source: https://habr.com/ru/post/1761122/


All Articles