Templates: Specialization

In this lesson, we will learn about template specialization.

Templates define the behavior of a family of classes and functions.

  • Special types, non-types, or templates as arguments must be treated special
  • You can fully specialize templates. Class templates can even be partially specialized.
  • The methods and attributes of specialization don’t have to be identical.
  • General or Primary templates can coexist with partially or fully specialized templates.

The compiler prefers fully specialized to partially specialized templates and partially specialized templates to primary templates.

Primary Template

The primary template has to be declared before the partially or fully specialized templates.

  • If the primary template is not needed, a declaration is sufficient.
template <typename T, int Line, int Column> class Matrix;
template <typename T>
class Matrix<T, 3, 3>{};

template <>class Matrix<int, 3, 3>{};

Partial Specialization

The partial specialization of a template

  • is only supported for class templates
  • has template arguments and template parameters

Get hands-on with 1000+ tech skills courses.