Explicit Instantiation Definition
An explicit instantiation definition forces the compiler to generate the code for the specified template arguments in the current translation unit, regardless of whether the template is actually used in that file. Syntax:Explicit Instantiation Declaration (extern template)
Introduced in C++11, an explicit instantiation declaration instructs the compiler not to implicitly instantiate the template in the current translation unit. It acts as a promise to the compiler that an explicit instantiation definition exists in exactly one other translation unit.
Syntax:
inline Caveat:
An explicit instantiation declaration does not suppress the instantiation of inline functions. If a template’s member functions are defined inline (such as inside the class body), the compiler will still instantiate them when called, regardless of the extern template declaration.
Example:
Technical Constraints and Rules
- One Definition Rule (ODR): There can be at most one explicit instantiation definition for a specific set of template arguments across the entire program. Violating this is an ODR violation (ill-formed, no diagnostic required). However, this frequently does not result in linker errors if the template members are implicitly or explicitly
inline. In such cases, the linker typically merges the weak symbols (COMDAT sections) without emitting a multiple definition error. - Visibility: The primary template definition must be visible to the compiler at the point of an explicit instantiation definition.
- Ordering: An explicit instantiation declaration must follow the template declaration. An explicit instantiation definition must follow the template definition.
- Specialization Conflict: You cannot explicitly specialize a template for a set of arguments if you have already explicitly instantiated it for those same arguments. Conversely, if an explicit instantiation follows an explicit specialization, the code is well-formed, but the explicit instantiation simply has no effect on that specialized entity.
Tired of Poor C++ Skills? Fix That With Deep Grasping!Learn More





