13

It was suggested to use explicit template instantiation to reduce compilation time. I am wondering how to do it. For example

// a.h
template<typename T> class A {...};
template class A<int>; // explicit template instantiation  to reduce compilation time

But in every translation unit where a.h is included, it seems A<int> will be compiled. The compilation time is not reduced. How to use explicit template instantiation to reduce compilation time?

Heyji
  • 1,113
  • 8
  • 26
user1899020
  • 13,167
  • 21
  • 79
  • 154

2 Answers2

19

Declare the instantiation in the header:

extern template class A<int>;

and define it in one source file:

template class A<int>;

Now it will only be instantiated once, not in every translation unit, which might speed things up.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • It will be instantiated in all source files with explicit template instantiation definition directive (`template class A;`). – Constructor Oct 08 '14 at 10:20
  • 1
    @Constructor: Indeed. If you do what the answer says, that will just happen once. – Mike Seymour Oct 08 '14 at 15:49
  • I only wanted to note that explicit template instantiation *declaration* is not a good protection of multiple instantiations of a template (accidental or intentional). – Constructor Oct 09 '14 at 07:00
  • Could you give a hint at good protection for that? Is there any at all? I typically use 2 header files -- the one which holds the template code, the other which includes the first and only contains the "extern template" explicit specilization declarations. A source file then includes the first one and does the explicit declaration and all other source files include the second with the "extern template" declarations. – Till Kolditz Mar 02 '17 at 12:06
12

If you know that your template will be used only for certain types, lets call them T1,T2, you can move implementation to source file, like normal classes.

//foo.hpp
template<typename T>
struct Foo {
    void f();
};

//foo.cpp
template<typename T>
void Foo<T>::f() {}

template class Foo<T1>;
template class Foo<T2>;
fghj
  • 8,898
  • 4
  • 28
  • 56
  • Shouldn't the implementation be in the form of `template void Foo::f() { }`? Note `Foo::` instead of `Foo::` – Xupicor Oct 27 '15 at 07:51