patterncppCritical
Storing C++ template function definitions in a .CPP file
Viewed 0 times
functioncppstoringtemplatefiledefinitions
Problem
I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example:
.h file
.cpp file
Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.
My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.
.h file
class foo
{
public:
template
void do(const T& t);
};.cpp file
template
void foo::do(const T& t)
{
// Do something with t
}
template void foo::do(const int&);
template void foo::do(const std::string&);Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.
My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.
Solution
The problem you describe can be solved by defining the template in the header, or via the approach you describe above.
I recommend reading the following points from the C++ FAQ Lite:
They go into a lot of detail about these (and other) template issues.
I recommend reading the following points from the C++ FAQ Lite:
- Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?
- How can I avoid linker errors with my template functions?
- How does the C++ keyword export help with template linker errors?
They go into a lot of detail about these (and other) template issues.
Context
Stack Overflow Q#115703, score: 326
Revisions (0)
No revisions yet.