I prefer to have all of my functions in the .cpp
file, regardless of whether they are template functions or regular functions. And there is a way to do that with some basic #ifndef
magic. Here's what you can do:
main.cpp
#include "myclass.hpp"
int main()
{
// ...
}
myclass.hpp
#ifndef MYCLASS
#define MYCLASS
template
class MyClass
{
T val;
public:
MyClass(T val_);
}
#define MYCLASS_FUNCTIONS
#include "myclass.cpp"
#endif
myclass.cpp
#ifndef MYCLASS_FUNCTIONS
#include "myclass.hpp"
// regular functions:
// ...
#else
// template functions:
template
MyClass::MyClass(T val_)
:val(val_)
{}
// ...
#endif
Here's how the precompiler sees it. We have two .cpp
files.
- When we compile main.cpp we:
- include
myclass.hpp
- check that
MYCLASS
is undefined, and it is
- define it
- give compiler the definitions of the generated class (from template class)
- include
myclass.cpp
- define
MYCLASS_FUNCTIONS
- check if
MYCLASS_FUNCTIONS
is defined, it is
- give compiler the definitions of the generated functions (from template functions)
- When we compile myclass.cpp
- check if
MYCLASS_FUNCTIONS
is defined, it isn't
- include
myclass.hpp
- check that
MYCLASS
is undefined, and it is
- define it
- give compiler the definitions of the class
- include
myclass.cpp
- include
myclass.hpp
again
- this time
MYCLASS
is defined so do nothing inside, return to myclass.cpp
- check if
MYCLASS_FUNCTIONS
is defined, it is
- give compiler the definition of the generated functions (from template functions)
- exit include twice
- pass to the compiler all the regular functions