Explicit Instantiation

You request explicit instantiation by using the explicit template instantiation syntax (as defined in the ANSI/ISO C++ International Standard) in your source file.

You can request explicit instantiation of a particular template class or a particular template function. In addition, member functions and static data members of class templates may be explicitly instantiated.

Explicit instantiation of a class instantiates all member functions and static data members of that class, regardless of whether or not they are used.

For example, following is a request to explicitly instantiate the Table template class with char*:

template class Table<char*>;

When you specify an explicit instantiation, you are asking the compiler to instantiate a template at the point of the explicit instantiation in the translation unit in which it occurs.

Usage

This might be useful when you are building a library for distribution and want to create a set of compiler-generated template specializations that you know will most commonly be used. Then when an application is linked with this library, any of these commonly used specializations need not be instantiated.

Another scenario might be a frequently used library that contains a repository of template specializations for your development team. Instantiating all such specializations in one, known translation unit would allow easy maintenance when changes are needed and eliminate cases of duplicate definition.

Performance

Although time is required to analyze and design code for explicit instantiation, compilation may be faster than for the equivalent implicit instantiation.

Examples

Following are the examples for explicit and implicit instantiation:

Class Template

Following are examples of explicit and implicit instantiation syntax for a class template:

template <class T> class Array;

// forward

 

// declaration

 

// for the

 

// Array class

 

// template

template <class T> class Array {/*...*/};

// definition

 

// of the Array

 

// class

 

// template

template class Array <int>;

// request to

 

// explicitly

 

// instantiate

 

// Array<int>

 

// template class

Array <char> tc;

// use of

 

// Array<char>

 

// template

Invoking Compile-Time Instantiation 133