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

Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at writeulearn@gmail.com along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.