Description
When a template is defined, normally there is a single definition to cover all possible template parameter types. For example, we might have a Vector<T> template, and the operation of inserting new elements into the template would be the same, whether T is an int or a class type or a single bit (bool).
But sometimes you want more flexibility than this default approach offers, and specializations are a way to achieve this. An example of a specialization of Vector would be:
template <> class Vector<bool> {
...
};
which says that whenever bool is the template argument to
Vector, use the specified alternative implementation instead.
In this particular example, one obvious use of specialization would be
to represent elements efficiently, for example in a single bit.
A variant of specializations is partial specialization, where a whole class of template parameters can be identified for special treatment. For example, a declaration like:
template <class T> class Vector<T*> {
...
};
means that this specialization is used for all template parameter types
that are pointers.
Such a specialization might be used for efficiency, or to provide
a different style of implementation.
Template functions can also be specialized. For example, with this template:
template <class T> bool less(T a, T b)
{
return a < b;
}
a specialization for const char* would be:
template <> bool less(const char* a, const char* b)
{
return strcmp(a, b) < 0;
}
In this case, the specialization is required for correct functioning.
The default implementation of less will simply compare the
pointer values themselves, rather than the characters pointed to.
Concept
The sample program defines a Vector template, and then declares two specializations of it. One is for bool parameters, and the other a partial specialization for all pointer types. The sample also illustrates the use of a specialization of less, as was discussed above.
Supported
Supported
Supported
