Partial Template Specialization - Templates and Specialization

Templates and Specialization

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.

Read more about this topic:  Partial Template Specialization