Using Extern Template to Optimize Template Instantiation
In C 11, extern template is a powerful keyword that can be used to avoid redundant instantiation of templates, particularly when multiple translation units (e.g., .cpp files) may include the same header file containing template definitions.
Concept of Extern Template
Extern template essentially informs the compiler that the current translation unit should not instantiate a specific template, even though it is declared in the included header. This is useful when you know that the template will be instantiated in a different translation unit of the same project.
Usage for Function Templates
For function templates, an extern template declaration can be used as follows:
#include "header.h" extern template void f<T>(); // Avoid instantiation in this translation unit
This indicates that the f template will be defined elsewhere in the project and should not be instantiated in the current file.
Usage for Class Templates
Similarly, for class templates, an extern template declaration takes the following form:
#include "header.h" extern template class foo<int>; // Avoid instantiation in this translation unit
This ensures that the foo template class is not instantiated in this particular translation unit.
Optimization Applications
Consider the following scenario:
// header.h template<typename T> void f();
// source1.cpp #include "header.h" void f<int>();
// source2.cpp #include "header.h" void f<string>();
Without extern template, both source1.cpp and source2.cpp will instantiate the f template, leading to multiple definitions and wasted compilation time. By using extern template in one of the files, we avoid this redundancy:
// source1.cpp #include "header.h" void f<int>();
// source2.cpp #include "header.h" extern template void f<int>(); void f<string>();
Key Points
The above is the detailed content of How Can Extern Templates Optimize Template Instantiation in C ?. For more information, please follow other related articles on the PHP Chinese website!