C++ -- Can I use a template function that is not implemented in a header file?
c++, templates
Solution
Its a common idiom to place template definitions into an `.inl` file along with inline function definitions, and include it at the end of `.h` file:
base.h
#ifndef BASE_H
#define BASE_H
class Base {
protected:
template <typename T>
void doStuff(T a, int b);
};
#include "base.inl"
#endif
base.inl
template <typename T>
void Base::doStuff(T a, int b) {
a = b;
}
Problem
Possible Duplicate: Storing C++ template function definitions in a .CPP file Why can templates only be implemented in the header file? Why should the implementation and the declaration of a template class be in the same header file? I have three files. In one, base.h, I have a class that has a member utilizing a template: ``` class Base { protected: template <class T> void doStuff(T a, int b); }; ``` In base.cpp, I implement Base::doStuff(): ``` #include "base.h" template <class T> void Base::doStuff(T a, int b) { a = b; } ``` I then try to use this in another class in my project: ``` #include "base.h" void Derived::doOtherStuff() { int c; doStuff(3, c); } ``` But I get a linking error that states that it can't find 'doStuff(int, int)' From what I've seen, this is not possible in C++03 without moving the implementation of this function into the header file. Is there a clean way to do this? (I'm fine with using C++11x features).
Related problems
- Why should the implementation and the declaration of a template class be in the same header file?
- Why can templates only be implemented in the header file?
- Storing C++ template function definitions in a .CPP file
- Why should the implementation and the declaration of a template class be in the same header file?
- Why can templates only be implemented in the header file?
- Storing C++ template function definitions in a .CPP file