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?
All the template parameters are fixed+known at compile-time. If there are compiler errors due to template instantiation, they must be caught at compile-time!
When a function template is first called for each type, the compiler creates an instantiation. Each instantiation is a version of the templated function specialized for the type. This instantiation will be called every time the function is used for the type.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation to handle a specific set of template arguments is called a specialization.
Template compilation requires the C++ compiler to do more than traditional UNIX compilers have done. The C++ compiler must generate object code for template instances on an as-needed basis. It might share template instances among separate compilations using a template repository.
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>;
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