extern template is a powerful C 11 keyword that allows developers to prevent the instantiation of a template in a specific compilation unit. This can be particularly useful when working with large codebases where multiple source files may instantiate the same template with different parameters, leading to duplicate code and increased compilation time.
In the case of function templates, extern template can be used to force the compiler not to instantiate a particular template when it knows that the function will be instantiated elsewhere. Consider the following example:
// header.h template<typename T> void ReallyBigFunction() { // Body }
// source1.cpp #include "header.h" void something1() { ReallyBigFunction<int>(); }
// source2.cpp #include "header.h" extern template void ReallyBigFunction<int>(); void something2() { ReallyBigFunction<int>(); }
Without extern template, the compiler would compile ReallyBigFunction
source1.o void something1() void ReallyBigFunction<int>() // Compiled first time source2.o void something2() void ReallyBigFunction<int>() // Compiled second time
Linking these files together would result in one copy of ReallyBigFunction
To avoid this issue, we can use extern template in source2.cpp:
// source2.cpp #include "header.h" extern template void ReallyBigFunction<int>(); void something2() { ReallyBigFunction<int>(); }
This will result in the following object files:
source1.o void something1() void ReallyBigFunction<int>() // Compiled just one time source2.o void something2() // No ReallyBigFunction<int> here because of the extern
When these object files are linked, the second object file will use the symbol from the first object file, avoiding duplicate code and reducing compilation time.
extern template can also be used with class templates to prevent the instantiation of specific class members. For example:
// header.h template<typename T> class Foo { public: T f(); };
// source1.cpp #include "header.h" Foo<int> foo1;
// source2.cpp #include "header.h" extern template class Foo<int>; Foo<int> foo2;
Without extern template, the compiler would compile the member function f for Foo
extern template is a valuable tool for avoiding duplicate code and reducing compilation time in C 11 projects. By selectively using extern template to prevent unnecessary template instantiations, developers can optimize the performance of their code.
The above is the detailed content of How Can `extern template` in C 11 Prevent Duplicate Template Instantiations and Reduce Compilation Time?. For more information, please follow other related articles on the PHP Chinese website!