Summary
This question is about achieving separate compilation of a single template class instantiation in a several different translation units.
Question
For non-template classes one can put definitions in several .cpp files and compile them separately. For instance:
file A.h:
class A {
public:
void func1();
void func2();
void func3() { /* defined in class declaration */}
}
file A1.cpp:
void A::func1() { /* do smth */ }
file A2.cpp:
void A::func2() { /* do smth else */ }
Now I tried to do something similar with template classes. Since I know exactly which instances I will need, I'm explicitly instantiating templates. I'm compiling each instantiation separately, because member functions contain rather large mathematical expressions, which could slow down compiler considerably on high optimization levels. So I tried the following:
file TA.h:
template <typename T>
class TA {
public:
void func1();
void func2();
void func3() { /* defined in class declaration */}
}
file TA1.cpp:
template <typename T>
void TA<T>::func1() { /* do smth */ }
template class TA<sometype>;
file TA2.cpp:
template <typename T>
void TA<T>::func2() { /* do smth else */ }
template class TA<sometype>;
It works with clang and GCC on Linux, but fails with GCC on Mac during linking during duplicate symbols error (in this example due to func3, which got instantiated in both TA1.cpp and TA2.cpp).
Then I stumbled upon this sentence in the standard:
C++11.14.7, paragraph 5:
For a given template and a given set of template-arguments,
-- an explicit instantiation definition shall appear at most once in a program,
-- ...
Does it mean that separate compilation of template classes is not possible (not allowed) even when using explicit instantiation (it is obviously not possible with implicit instantiation)?
PS I don't care since I've got my answer, but whoever thinks it is answered in here https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file is wrong.