Tag Archives: template specialization

template specialization

The idea of template specialization is to override the default template implementation to handle a particular type in a different way.

Example:

Template definition

template <typename T>
class vector
{
private:
T* vec_data; // we’ll store the data as block of dynamically allocated
// memory
int length; // number of elements used
int vec_size; // actual size of vec_data
};

Template Specialization
template <>  // Empty Template parameter means template specialization
class vector <bool>
{
// interface

private:

unsigned int *vector_data;
int length;
int size;
};
The bool type takes 1 byte, but actually one byte could store 8 bools. When you need an array of bools it may seem reasonable to pack more of them in a single byte in order to reduce the memory consumption. The specialization here allows to achieve exactly this.

The compiler will pick the most specific template specialization since regular functions will always be chosen instead of templated versions if they match.
the most specific template specialization is the one whose template arguments would be accepted by the other template declarations, but which would not accept all possible arguments that other templates with the same name would accept.
It’s worth pointing out that the salient reason for the specialization is :

  • to allow for a efficient implementation for a particular type
  • if you have a template type that relies on some behavior that was not implemented in a collection of classes you’d like to store in that template
  • If you wanted to add extra methods to one templated class

Example showing the explained distiction:

template <int, int> class MyClass; // <– primary template

template <int> class MyClass<int, 4>; // <– partial specialization

template <> class MyClass<1,2>; // <– specialization