Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use explicit template instantiation to reduce compilation time?

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?

like image 718
user1899020 Avatar asked Oct 08 '14 01:10

user1899020


People also ask

Are templates resolved at compile-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!

How the instantiation of function template happens?

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.

What is instantiation of a template?

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.

How are templates compiled in C++?

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.


1 Answers

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>;
like image 157
fghj Avatar answered Sep 22 '22 19:09

fghj