Understanding Explicit Specialization

A template specialization is the definition created from a template instantiation. The template that is being specialized is called the primary template. We can provide an explicit specialized definition for a given set of template arguments, therefore overwriting the implicit code the compiler would generate instead. This is the technique that powers features such as type traits and conditional compilation, which are metaprogramming concepts we’ll explore in the “Type Traits and Conditional Compilation” section.

There are two forms of template specialization: explicit (full) specialization and partial specialization. We’ll look at both of these in detail in this lesson and the next lesson, respectively.

Explicit specialization

Explicit specialization (also called full specialization) occurs when we provide a definition for a template instantiation with the full set of template arguments. The following can be fully specialized:

  • Function templates

  • Class templates

  • Variable templates (as of C++14)

  • Member functions, classes, and enumerations of a class template

  • Member function templates and class templates of a class or class template

  • Static data members of a class template

Let’s start by looking at the following example:

Get hands-on with 1400+ tech skills courses.