Suppose I have a class with a method template:
//file: X.h
class X{
int x;
//... more members and non-template functions
template<typename T>
void foo(T t){ //Error, cannot define the method here. Declaration is okay
Y y = ...;
}
}
//file Y.h
class Y {
X x;
}
Due to circular class dependencies (the body of foo depends on Y and Y depends on X), I cannot define the method template foo where I declared it (Please do not question the design now).
So, where to put the definition of foo in this case? I cannot put it to the other definitions into the .cpp file or linking will fail.
My solution is to create a new header file, e.g. “X.hpp” and only add the definition of the template method into it. In this file, I include “X.h” and “Y.h”. Now, whenever I need the class X, I simply include only “X.hpp” which will in turn include the other necessary h files.
So my question is: Is this the correct/best way to do it? It somehow bugs me that I have a .hpp file for only a single method template definition, but it seems to be the only possible way in case of circular type dependencies. Please again: Do not question the design by saying “it would be best to avoid circular type dependencies” or stuff like that. The question is: IF I have these dependencies, what is the best way to handle single method templates.
Without questioning the design:
There’s no need for the extra file.