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).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With