On my C++ project, I recently stumbled upon a little problem: Templates.
I declared a class, Data in my header file (which is shared by each .cpp), and gave it a template function. I implemented it in data.cpp. I soon remembered how templates are compiled on the spot, when they are referred to, and this breaks the declaration/implementation separation done with .h and .cpp files.
So I thought of a little work around, by putting:
class Data {
template<typename T> void myFunc(T in);
};
#define __DATA_TEMPLATE_IMPL
#include "Data.cpp"
#undef __DATA_TEMPLATE_IMPL
In header.h and:
#ifndef __DATA_TEMPLATE_IMPL
// non-template functions and other stuff....
#else
template<typename T>
void Data::myFunc(T in) {
// implementation of template function
}
#endif
It is a big workaround, and to the compiler, it looks as if the code between #else
and #endif
where moved to the header file.
Two questions:
Do you see anything wrong with this? Can you think of any reason this might be wrong, inneficient, or whatever?
Is there any better way (besides actually putting the implementation in the header file)?