Template specialization
Specialization gives a template a different implementation for particular template arguments. The generic version stays as the fallback, and the compiler picks the most specific match for the types you actually use.
Detailed Explanation
A generic implementation is right most of the time and wrong occasionally. You write a Serializer<T> that walks members reflectively, but for bool you want a single byte, and for std::string you want a length prefix. Specialization is the mechanism for saying "for this type, do it differently" without renaming the function or forcing callers to know.
Full specialization, also called explicit specialization, fixes every template parameter. You write template <> struct Serializer<bool> { ... }; and supply a complete, unrelated body. The primary template is not reused; the specialization replaces it entirely, including its members. Nothing forces the specialization to have the same interface as the primary template, which is exactly the trap discussed below.
Partial specialization fixes some parameters and leaves others open. template <typename T> struct Serializer<std::vector<T>> covers every vector regardless of element type. template <typename T> struct Serializer<T*> covers every pointer. This is where specialization earns its keep, because it lets you match a shape rather than a single type.
Here is the rule people trip on: only class templates support partial specialization. Function templates support full specialization but not partial. If you write what looks like a partially specialized function template, you have actually written an overload, and overload resolution has different and less predictable rules than specialization ordering. The guidance is direct: do not specialize function templates. Overload them instead, or make the function a thin wrapper over a class template that you specialize. Overloading is checked earlier, participates in ordinary overload resolution, and does not surprise you when a specialization is declared after the call site.
std::vector<bool> is the standard library's own full specialization and its most cited mistake. To save memory it packs eight booleans per byte. That makes it not a container of bool at all. operator[] cannot return bool& because a bit has no address, so it returns a proxy object. &v[0] does not give you a bool*. auto b = v[0]; gives you the proxy, not a copy of the value, and the proxy dangles if the vector reallocates. Generic code written against std::vector<T> breaks when T is bool. The lesson is not that specialization is bad but that a specialization which changes the observable contract poisons every generic algorithm that trusted the contract. If you need packed bits, use std::bitset or std::vector<char> and say so.
Modern C++ has better tools for most of what specialization used to do. Tag dispatch picks an overload by passing an empty tag type derived from a trait, which keeps everything in the overload resolution system. if constexpr, added in C++17, discards the untaken branch at compile time, so a single function body can handle several types without any separate specialization at all. C++20 concepts constrain and order overloads directly and give readable errors. Reach for full or partial specialization when you are specializing a class template or a type trait, which is still its natural home; reach for if constexpr or a constrained overload when you are writing a function.
Code Examples
#include <iostream>
#include <string>
#include <vector>
// Primary template.
template <typename T>
struct TypeName {
static std::string get() { return "unknown"; }
};
// Full specialization: every parameter is fixed.
template <>
struct TypeName<int> {
static std::string get() { return "int"; }
};
// Partial specialization: matches any vector, element type still open.
template <typename T>
struct TypeName<std::vector<T>> {
static std::string get() { return "vector<" + TypeName<T>::get() + ">"; }
};
int main() {
std::cout << TypeName<int>::get() << '\n'; // int
std::cout << TypeName<std::vector<int>>::get() << '\n'; // vector<int>
std::cout << TypeName<std::vector<double>>::get() << '\n'; // vector<unknown>
}#include <type_traits>
#include <string>
// Do NOT specialize this function template. Use if constexpr (C++17) instead:
// the untaken branch is discarded, so it need not even compile for that type.
template <typename T>
std::string describe(const T& value) {
if constexpr (std::is_integral_v<T>) {
return "integer " + std::to_string(value);
} else if constexpr (std::is_floating_point_v<T>) {
return "real " + std::to_string(value);
} else {
return "object";
}
}
// describe(42) -> "integer 42"
// describe(1.5) -> "real 1.500000"
// describe("hi") -> "object" (to_string is never instantiated here)Common Gotchas
Specializing a function template is almost always the wrong tool
function templates cannot be partially specialized, and a full specialization does not participate in overload resolution the way people expect, so an unrelated overload can win. Write an overload or a constrained function instead.
A specialization declared after first use is ill-formed, no diagnostic required
if a translation unit instantiates `Serializer<bool>` before it sees `template <> struct Serializer<bool>`, the program is invalid and the compiler is not obliged to tell you. Declare specializations in the same header as the primary template.
Specializing standard library templates is allowed but narrow
you may specialize things like `std::hash` for your own type, and you must do it inside `namespace std` for that specific case. Adding new overloads to `namespace std` is undefined behavior.