Using extern template to Avoid Template Instantiation (C 11)
In object-oriented programming, templates play a crucial role in providing generic solutions that work with different data types. However, when multiple source files instantiate templates with the same parameters, it can lead to multiple definitions and increased compile time.
The extern template keyword can be used to address this issue and avoid unnecessary template instantiation. It instructs the compiler not to instantiate a particular template specialization within the current translation unit. Instead, the compiler relies on the template being instantiated in another source file or linked library.
Function Templates
When dealing with function templates, extern template can be used to force exclusion of explicit template instantiation. For instance, consider the following code snippet:
// header.h template<typename T> void f(); // source1.cpp #include "header.h" void f<int>(); // Explicit instantiation // source2.cpp #include "header.h" extern template void f<int>(); // Prevents explicit instantiation void g() { f<int>(); }
In this scenario, source1.cpp explicitly instantiates f
Class Templates
The same principle applies to class templates. extern template can be used to avoid multiple instantiations of the same template class with the same parameters. Consider the following example:
// header.h template<typename T> class foo { public: void f(); }; // source1.cpp #include "header.h" template class foo<int>; // Explicit instantiation // source2.cpp #include "header.h" extern template class foo<int>; // Prevents explicit instantiation void h() { foo<int> obj; }
Here, extern template in source2.cpp prevents the explicit instantiation of foo
Benefits of Using extern template
Using extern template provides several benefits:
Conclusion
extern template is a powerful keyword that allows developers to control template instantiation and optimize compile time. By using it judiciously, developers can ensure that templates are used efficiently and avoid the pitfalls of multiple instantiations, resulting in faster compilation and smaller executables.
The above is the detailed content of How Does `extern template` Avoid Redundant Template Instantiation in C ?. For more information, please follow other related articles on the PHP Chinese website!