C++ - circular dependencies
Since the down of time mankind seek the solution to the circular dependencies in C++. Well - may be ot exactly since the "down of time" and definitly not the whole of the mankind - but it have been "always" a problem.
Traditional solution was to forward-declarate it:
- class A;
- class B
- {
- public:
- B(A *) {}
- };
- class A
- {
- static B b;
- };
However it have its limitations. For example B cannot call A methods making such solutions useless. Other solution is spliting functions and class declaration - however it may cause problems if they will not match (for example some functions remain undefined):
- class A;
- class A
- {
- static B<A> b;
- public:
- void doIt();
- };
- class B
- {
- public:
- B(A *);
- void doSomething();
- };
- void A::doIt()
- {
- b.doSomething();
- }
- B::B(A *a)
- {
- if(a != NULL)
- a->doit();
- }
- void B::doSomething()
- {
- }
There is solution, at least working on gcc 4.4. Let's define B as a template:
- template<typename A>
- class B
- {
- public:
- B(A *a)
- {
- if(a != NULL)
- a->doit();
- }
- void doSomething() {}
- };
- class A
- {
- static B<A> b;
- public:
- void doit()
- {
- b.doSomething();
- }
- };
Probably we consider writing each time ]]> waste of space. We can simply forward-declare class and set the default arguments:
- class A;
- template<typename A = ::A>
- class B
- {
- public:
- B(A *a)
- {
- if(a != NULL)
- a->doit();
- }
- void doSomething() {}
- };
- class A
- {
- static B<A> b;
- public:
- void doit()
- {
- b.doSomething();
- }
- };
Tagged by: C++, dependencies, templates,
Comments
You can track the comments by RSS feed . You can comment or post a trackback from your blog.
There is no comments. Yours can be the first.
Add a comment