Explicit instantiation

suggest change

An explicit instantiation definition asks the compiler to instantiate a class, function, or variable template for specific template arguments. Variable templates are C++14. extern template, below, is C++11. Code in other translation units can then refer to that specialization. This technique can keep a template definition out of a public header when the supported argument types form a known, finite set. For example:

// print_string.h
template <class T>
void print_string(const T* str);

// print_string.cpp
#include "print_string.h"

template <class T>
void print_string(const T* str) {
    // implementation
}

template void print_string(const char*);
template void print_string(const wchar_t*);

Because print_string<char> and print_string<wchar_t> are explicitly instantiated in print_string.cpp, callers can link to those specializations even though the template definition is not in the header. Without the explicit instantiation definitions, calls from another translation unit could produce unresolved-symbol linker errors.

If an explicit instantiation definition is preceded by the extern keyword, it becomes an explicit instantiation declaration instead. The presence of an explicit instantiation declaration for a given specialization prevents the implicit instantiation of the given specialization within the current translation unit. Instead, a reference to that specialization that would otherwise cause an implicit instantiation can refer to an explicit instantiation definition in the same or another TU.

foo.h

#ifndef FOO_H
#define FOO_H
template <class T> void foo(T x) {
    // complicated implementation
}
#endif

foo.cpp

#include "foo.h"
// explicit instantiation definitions for common cases
template void foo(int);
template void foo(double);

main.cpp

#include "foo.h"
// we already know foo.cpp has explicit instantiation definitions for these
extern template void foo(double);
int main() {
    foo(42);   // instantiates foo<int> here;
               // wasteful since foo.cpp provides an explicit instantiation already!
    foo(3.14); // does not instantiate foo<double> here;
               // uses instantiation of foo<double> in foo.cpp instead
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents