This question is closed because it is considered a duplicate of:
- C++ cyclical header dependency
- cyclic dependency between header files
- C++ error: 'Line2' has not been declared
However the other question are different from my: they ask a different case and the answer do not work with my problem. Their answer suggest to put the function into a .cpp
file and to define the class before to declare it. I cannot put the function in .cpp
because my class is a template, and I already define the class, but it is not useful.
I have two header file a.h
and b.h
. In they are defined two template class A
and B
.
A function of A
need work with object of B
and viceversa. Since they are template class, I can not put the function in .cpp
file, it must stay in header, and I have a big headache because of the order of the inclusion.
What is a good methodology to solve this problem?
Currently I move function definition around and find a way to include the headers in the correct order, but this become always more complex. Moreover I do not like to have function definition far from class declaration (for example in other file).
Example code:
a.h
#ifndef A_H
#define A_H
#include <iostream>
#include "b.h"
template< typename T > class B;
template< typename T >
class A {
public:
B<void> *b;
void f();
void g();
};
template< typename T > void A<T>::f() {
std::cout << "A::f" << std::endl;
b->f();
}
template< typename T > void A<T>::g() {
std::cout << "A::g" << std::endl;
}
#endif
b.h
#ifndef B_H
#define B_H
#include <iostream>
#include "a.h"
template< typename T > class A;
template< typename T >
class B {
public:
A<void> *a;
void f();
void g();
};
template< typename T > void B<T>::f( ) {
std::cout << "B::f" << std::endl;
}
template< typename T > void B<T>::g( ) {
std::cout << "B::g" << std::endl;
a->g();
}
#endif
main.cpp
#include "a.h"
#include "b.h"
int main( ) {
A<void> a;
B<void> b;
a.b = &b;
b.a = &a;
a.f();
b.g();
return 0;
}
This not work because a.h
include b.h
. b.h
then can not include a.h
and thus B::g
is error.
For this example code I can move B::g
in main.cpp
or at the end of a.h
, but with more complex program this is not easy.