Partial template specialization

From Wikipedia, the free encyclopedia
Jump to: navigation, search

Partial template specialization is a particular form of class template specialization. Usually used in reference to the C++ programming language, it allows the programmer to specialize only some arguments of a class template, as opposed to explicit specialization, where all the template arguments are provided.

Templates and specialization[edit]

Class templates are really meta-classes: they are partial abstract data types that provide instructions to the compiler on how to create classes with the proper data members. For example, the C++ standard containers are class templates. When a programmer uses a vector, one instantiates it with a specific data type, for example, int, string or double. Each type of vector results in a different class in the compiler's object code, each one working with a different data type.

If one knows that a class template will be used with a specific data type fairly often and this data type allows some optimizations (e.g. bit shifting with integers, as opposed to multiplying or dividing by 2), one may specialize the template by specifying another class template that is identical but by specifying the parameter types. When the compiler sees such a class template instantiated in code, it will generally choose the most specialized template definition that matches the instantiation. Therefore, an explicit specialization (one where all the template arguments are specified) will be preferred to a partial specialization if all the template arguments match.

Partial specialization[edit]

Templates can have more than one parameter type. Some older compilers allow one only to specialize either all or none of the template's parameters. Compilers that support partial specialization allow the programmer to specialize some parameters while leaving the others generic. Until recently most compilers did not support this feature well (at best) or ignored such specializations (at worst).

At least the GNU, Intel, Comeau, and Microsoft compilers fully support partial specialization of templates.


template <class K>
struct StringMap : public std::map<K, std::string> {};

StringMap class is a partial specialization of std::map (specializes the 'value' part of the map)
Note StringMap is actually derived from std::map to create a new partially specialized class with a different name without having resort to other tricks such as namespaces.

template<class K>
map <K, std::string> {};

would create a partial specialization of map with the same name.