Using extern template to Avoid Template Instantiation
Template instantiation is a crucial step in C programming, where specific template instances are created at compile time. In certain scenarios, it becomes necessary to control template instantiation to optimize compilation time and avoid redundant definitions. This is where the extern template keyword comes into play.
Extern Templates for Function Templates
When used with function templates, extern template instructs the compiler not to instantiate the specified template within the current translation unit. It signals that an instantiation of that template will be found elsewhere in the program. This is particularly useful in scenarios where multiple source files instantiate the same template with identical parameters, leading to multiple definitions that the compiler must discard.
Example:
Consider the following code snippet:
In this case, the extern template in source2.cpp informs the compiler that the f
Extern Templates for Class Templates
Similar to function templates, extern template can also be used with class templates. This is done to avoid multiple instantiations of template classes with the same parameters.
Example:
Here, the extern template in source2.cpp ensures that the MyClass
Guidelines for Using extern template
The above is the detailed content of How Can `extern template` Prevent Redundant Template Instantiation in C ?. For more information, please follow other related articles on the PHP Chinese website!