Suppose I have fileA.h
which declares a class classA
with template function SomeFunc
. This function is implemented directly
As Anthony Williams says, the extern template
construct is the correct way to do this, but since his sample code is incomplete and has multiple syntax errors, here's a complete solution.
fileA.h:
namespace myNamespace {
class classA {
public:
template void SomeFunc() { ... }
};
// The following line declares the specialization SomeFunc().
template <> void classA::SomeFunc();
// The following line externalizes the instantiation of the previously
// declared specialization SomeFunc(). If the preceding line is omitted,
// the following line PREVENTS the specialization of SomeFunc();
// SomeFunc() will not be usable unless it is manually instantiated
// separately). When the preceding line is included, all the compilers I
// tested this on, including gcc, behave exactly the same (throwing a link
// error if the specialization of SomeFunc() is not instantiated
// separately), regardless of whether or not the following line is included;
// however, my understanding is that nothing in the standard requires that
// behavior if the following line is NOT included.
extern template void classA::SomeFunc();
}
fileA.C:
#include "fileA.h"
template <> void myNamespace::classA::SomeFunc() { ... }