Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 171 ยท Templates and Generic Programming

Template Specialization

Learn C++ template specialization - full and partial specialization of class templates, specializing function templates, and when overloading is the better choice.

A template is written once for "any type". Usually that's exactly what you want, but sometimes one particular type needs different behavior: a different storage layout, a faster algorithm, or a more useful description. Template specialization lets you say "for this specific type, use this definition instead". The standard library does it all the time: std::hash<int> and std::hash<std::string> are separate specializations, and std::vector<bool> is famously specialized to pack bits.

In this lesson you'll learn full (explicit) specialization, where every template argument is fixed, and partial specialization, where you match a whole family of types such as "any pointer" or "any pair". You'll also see why function templates are normally overloaded rather than specialized, and how to plug your own types into standard templates like std::hash and std::formatter. This builds on Class Templates.

Full specialization of a class template

You start with the primary template: the general definition. A full specialization begins with an empty template header, template <>, and lists the exact arguments after the name.

C++ A primary template and full specializations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

TypeName<const int> falls back to the primary template: const int and int are different types, and full specializations only match exactly. Partial specialization, later in this lesson, can match "any const type" in one go.

A specialization is a completely separate class. It doesn't inherit anything from the primary template: not members, not base classes, not even the same interface. If the primary has size() and your specialization forgets it, code that calls size() on the specialized type simply fails to compile. Keep specializations interface-compatible with the primary, or users of your template will be surprised.

Specializing a single member

You don't always need to replace the whole class. You can fully specialize just one member function of a class template for one set of arguments; the rest of the class comes from the primary template.

C++ Specializing one member function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Partial specialization

A partial specialization still has template parameters, but it constrains the shape of the argument. You write the parameters you still need in the header, and a pattern after the name:

C++
template <typename T> struct Traits;               // primary
template <typename T> struct Traits<T*>;           // any pointer
template <typename T> struct Traits<const T>;      // any const type
template <typename A, typename B>
struct Traits<std::pair<A, B>>;                    // any pair
template <typename T, std::size_t N>
struct Traits<std::array<T, N>>;                   // any std::array

When you use the template, the compiler collects every specialization that matches and picks the most specialized one. int* matches both the primary and T*; T* wins because it's more specific. If two partial specializations match equally well (neither is more specialized than the other), the use is ambiguous and won't compile.

C++ Partial specializations match families of types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Each specialization peels off one layer and recurses on the rest, so arbitrarily nested types are described correctly. Compare const int* (pointer to const int) and int* const (const pointer to int): the patterns T* and const T read the declaration exactly like the rules in const with Pointers and References. std::map<int, int> has no matching specialization, so it gets the primary template's plain "value".

This "match a pattern, recurse on the parts" technique is the heart of many standard type traits. std::remove_pointer, std::is_pointer and std::remove_const are implemented as tiny partial specializations; see Type Traits and Metaprogramming.

Rules for partial specialization

  • Only class templates (and variable templates) can be partially specialized. Function templates can't.
  • The specialization must be declared before the first use that would pick it; otherwise that use silently got the primary template, and your program is ill-formed. Put specializations right after the primary template, in the same header.
  • Default template arguments belong on the primary template only.

Specializing function templates: prefer overloading

You can fully specialize a function template:

C++
template <typename T>
void show(T value) { std::println("generic: {}", value); }

template <>
void show<bool>(bool value) { std::println("bool: {}", value ? "yes" : "no"); }

But it's rarely the best tool. Function template specializations don't take part in overload resolution. The compiler first picks the best primary template (or plain function) among the overloads, and only then checks whether that template has a specialization for the deduced arguments. This leads to surprising results when specializations and overloads mix.

C++ Why overloading beats function specialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Now imagine the specialization is written as template <> void f(int*) (letting the compiler deduce the arguments) and placed above template <typename T> void f(T*). At that point only (a) exists, so it specializes (a) with T = int*. Then f(&x) prints (b): overload resolution picks (b) as the better primary and never looks at (a)'s specializations, so your specialization is silently ignored. The meaning of your code depends on declaration order. That's why the common advice is:

  • For functions, overload. A plain non-template void show(bool) is clearer, participates in overload resolution normally, and wins ties against templates.
  • Use if constexpr when only a small part of a function differs by type. See Compile-Time Programming.
  • Use constraints (requires std::integral<T>) to select between template overloads by category of type. See Concepts and Constraints.
  • If you truly need specialization for a function, put the logic in a class template's static member and specialize the class. Class specialization (including partial) has no such pitfalls.

Specializing standard library templates

You may not add new things to namespace std, but you may specialize certain standard templates for your own types. The two you'll use most are std::hash, so your type can be a key in std::unordered_map, and std::formatter, so std::println can print it.

C++ std::hash and std::formatter for your own type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The syntax template <> struct std::hash<Coord> (a qualified name, allowed since C++17) avoids opening namespace std { ... } yourself. Inheriting from std::formatter<std::string> reuses its parsing of width, fill and alignment, so {:>10} works for free. The string formatting lesson covers format specs in detail.

Rules for specializing standard templates: the specialization must depend on at least one user-defined type (you can't specialize std::hash<int>), and it must meet the template's requirements. A std::hash must be callable on const objects, never throw, and give equal hashes to equal values.

Specialize, overload or constrain?

Situation Best tool
A class template needs a different layout or algorithm for one type Full specialization of the class
Behavior for a family of types (all pointers, all pairs, all arrays) Partial specialization of a class
A function needs different behavior for one type A plain overload
A function differs slightly by type inside one body if constexpr
Different function implementations for categories (integers, ranges) Concepts / requires on overloads
Plug your type into the standard library Specialize std::hash, std::formatter and friends

A note on std::vector<bool>

std::vector<bool> is a full specialization that stores one bit per element. It saves memory, but it breaks the interface: v[0] returns a proxy object instead of a bool&, so bool& r = v[0]; doesn't compile and auto x = v[0]; gives you a proxy that still refers into the vector. It's the classic example of why a specialization should keep the primary's interface. If you need real bool elements, use std::vector<char> or std::deque<bool>; for fixed-size bit sets, use std::bitset.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With a primary template <typename T> struct Name and a full specialization template <> struct Name<int>, which type uses the primary template?

    Full specializations match only the exact type. const int is a different type from int, so it falls back to the primary template.
  2. 2. Which specialization does Describe<int**> pick, given the primary and template <typename T> struct Describe<T*>?

    int** is a pointer to int*, so it matches T* with T = int*. If the specialization recurses on Describe<T>, the inner layer is handled on the next step.
  3. 3. Which of these cannot be partially specialized?

    Only class templates (struct included) and variable templates can be partially specialized. For functions, use overloading or constraints.
  4. 4. Why is overloading usually preferred over specializing a function template?

    The compiler first chooses among primary templates and plain functions, then looks for a matching specialization of the chosen template. Plain overloads are considered directly.
  5. 5. Which specialization in namespace std is allowed?

    You may specialize standard templates for your own types as long as the specialization meets the template's requirements. Specializing for built-in types or adding new names to std is not allowed.

Summary

  • A full specialization (template <> struct X<int>) replaces the primary template for one exact set of arguments; it's a separate class that inherits nothing.
  • You can fully specialize a single member function of a class template and keep the rest.
  • A partial specialization (template <typename T> struct X<T*>) matches a family of types; the most specialized match wins, and equal matches are ambiguous.
  • Only class and variable templates can be partially specialized. Declare specializations right after the primary.
  • For functions, prefer plain overloads, if constexpr or concepts over specialization, which skips overload resolution.
  • Specialize std::hash and std::formatter (for your own types) to plug them into unordered containers and std::format.
  • Keep a specialization's interface compatible with the primary; std::vector<bool> shows what happens when it isn't.

Next: Concepts and Constraints, the modern way to say which types a template accepts.