Summary
This issue is to achieve a separate compilation of one instance of the template class in several different translation units.
Question
For non-template classes, you can put the definitions in multiple .cpp files and compile them separately. For example:
Ah file:
class A { public: void func1(); void func2(); void func3() { /* defined in class declaration */} }
A1.cpp file:
void A::func1() { /* do smth */ }
A2.cpp file:
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 explicitly create the templates. I compile each instance separately, because member functions contain fairly large mathematical expressions that can significantly slow down the compiler at high levels of optimization. So I tried the following:
TA.h file:
template <typename T> class TA { public: void func1(); void func2(); void func3() { /* defined in class declaration */} }
TA1.cpp file:
template <typename T> void TA<T>::func1() { /* do smth */ } template class TA<sometype>;
TA2.cpp file:
template <typename T> void TA<T>::func2() { /* do smth else */ } template class TA<sometype>;
It works with clang and GCC on Linux, but it doesnโt work with GCC on Mac during binding during duplicate character errors (in this example, because of func3, which received an instance in both TA1.cpp and TA2.cpp).
Then I came across this sentence in the standard:
C ++ 11.14.7, paragraph 5:
For a given template and a given set of argument templates,
- the definition of an explicit instantiation should appear no more than once in the program,
-...
Does this mean that separate compilation of template classes is impossible (not allowed) even when using an explicit instance (this is clearly impossible with an implicit instance)?
PS I donโt care, since I got my answer, but whoever thinks they are responding to this is https://stackoverflow.com/a/166129/
c ++ templates explicit-instantiation
Vayun
source share