Usually in C++ when I need interdependencies between classes, I use forward declarations in the header files and then include both header files in each cpp file.
However this approach breaks when working with templates. Because templates have to be entirely in the header files (not counting the case when I put the code into cpp and enumerate template class A<T>;
for each supported T
- this is not always feasible, e.g. when T
is a lambda).
So is there a way to declare/define interdependent templates in C++?
Code example
template<typename T> struct B;
template<typename T> struct A {
void RunA(B<T> *pB) {
// need to do something to B here
}
};
template<typename T> struct B {
void RunB(A<T> *pA) {
// need to do something to A here
}
};
If I start doing something to B
in RunA()
, I think, I will get a "missing definition" error because only forward declaration of B is available by the time RunA()
is compiled.
Perhaps there is some trick to organize header files e.g. by splitting each header into class definition and method definition files, and then including them in some fancy way. Or maybe something can be done via a third/fourth class. But I can't imagine how specifically to do this.
C++11/14/17 are ok (specifically, it's MSVC++2017, toolset v141).