C++ Migration Guide

Explicit Instantiation and Specialization

In the ARM, and in the 4.2 compiler, there was no standard way to request an explicit instantiation of a template using the template definition. The C++ standard, and the 5.0 compiler in standard mode, provide a syntax for explicit instantiation using the template definition; the keyword template followed by a declaration of the type. For example, the last line in the following code forces the instantiation of class MyClass on type int, using the default template definition.


template<class T> class MyClass {
    ...
};
template class MyClass<int>; // explicit instantiation 

The syntax for explicit specializations has changed. To declare an explicit specialization, or to provide the full definition, you now prefix the declaration with template<>. (Notice the empty angle brackets.) For example:


// specialization of MyClass
class MyClass<char>;         // old-style declaration
class MyClass<char> { ... }; // old-style definition
template<> class MyClass<char>;         // standard declaration
template<> class MyClass<char> { ... }; // standard definition

The declaration forms mean that the programmer has somewhere provided a different definition (specialization) for the template for the provided arguments, and the compiler is not to use the default template definition for those arguments.

In standard mode, the 5.0 compiler accepts the old syntax as an anachronism. The 4.2 compiler accepts the new specialization syntax, but does not treat code using the new syntax correctly in every case. (The standard changed after the feature was put into the 4.2 compiler.) For maximum portability of template specialization code, you can add statements similar to the following to a project-wide header:


#ifdef OLD_SPECIALIZATION_SYNTAX
#define Specialize
#else
#define Specialize template<>
#endif

Then you would write, for example:

Specialize class MyClass<char>; // declaration