I was wondering in which case the explicit instantiation of a class or function template must be used? Or otherwise what is the advantage of using explicit instantiation?
I was wondering in which case the explicit instantiation of a class or function template must be used? Or otherwise what is the advantage of using explicit instantiation?
To save compilation time, or to hide an implementation
For example:
Suppose you have code lib calculation matrix. It works with the choice, float, double and long double. Of course not to 3x rewrite the same code, you have made a template.
But now, the problem is that you already do not want to release the source code (or with templates, and export support is required) and then you do not want your template is instantiated with a type other than the 3 planned.
To be restricted to 3 types, there is in playing on static_assert or any other equivalent system. But to hide the code, there is only one way: just deliver the statements of the code, without implementation, and explicitly instantiate your template with the 3 types in a lib, which will be provided.
It allows also to win perfs: the compiler does not generate code to instantiate it every time a template, since the code it is not available. This is the linker that will work with the lib provided only once.
Otherwise, each unit of compilation, all templates are instantiated and generate the code, then the linker at the end is several instantiations and needs with a single linker. It takes a long time.
What is the interest of the manufacturer only instantiate a class template explicitly, and not the whole class:
template MyClass<double>::MyClass(); // generate constructor
vs
template class MyClass<long>; // generate the whole class
In large projects, where hundreds of source files have to be compiled on every build, the long compilation time can be reduced significantly if templates are explicitly instantiated all at once. This is because when the compiler has to instantiate a template, its thread of execution is interrupted by the need to generate the code for that template specialization (template for a specific type), and only then can it resume parsing. When hundreds of sporadic templates are to be instantiated, it can make a difference. Therefore, it's best to instantiate all templates in one source file explicitly, freeing the compiler from repeated interruption of its processing.
Source: devx
Bookmarks