Explicit instantiation

To instantiate templates explicitly, include the template definition file in a source file, and write a template instantiation statement for every instantiation. The syntax for a class template instantiation is as follows:

template class class-name<templ-specs>;

The syntax for a function template instantiation is as follows:

template return-type func-name<templ-specs>(arg-specs);

Listing 1 shows how to explicitly instantiate the templates in Listing 3.9 and Listing 3.10.

Listing 1. myinst.cp: Explicitly Instantiating Templates

#include "templ.cp"

template class Templ<long>; // class instantiation
template long Max<long>(long,long); // function instantiation

When you explicitly instantiate a function, you do not need to include in templ-specs any arguments that the compiler can deduce from arg-specs. For example, in Listing 1 you can instantiate Max<long>() like this:

template long Max<>(long, long);
// The compiler can tell from the arguments
// that you are instantiating Max<long>()

Use explicit instantiation to make your program compile faster. Because the instantiations can be in one file with no other code, you can even put them in a separate library.

The compiler also supports the explicit instantiation of non-template members. Listing 2 shows an example.

Listing 2. Explicit Instantiation of Non-Template Members

template <class T> struct X {
static T i;
};

template <class T> T X<T>::i = 1;
template char X<char>::i;

NOTE Explicit instantiation is not in the ARM but is part of the ISO C++ standard.