Template Specialization
Template specialization lets you provide custom behavior for specific template arguments. Use it when the generic implementation is not correct or not optimal for a known type.
Full Specialization
Full specialization replaces the primary template for an exact type.
#include <iostream>
template <typename T>
struct Printer {
static void print(const T& value) {
std::cout << "generic: " << value << "\n";
}
};
template <>
struct Printer<bool> {
static void print(bool value) {
std::cout << (value ? "true" : "false") << "\n";
}
};
Partial Specialization
Partial specialization customizes only part of a template argument pattern.
#include <memory>
template <typename T>
struct TypeInfo {
static constexpr const char* name = "value type";
};
template <typename T>
struct TypeInfo<T*> {
static constexpr const char* name = "raw pointer";
};
template <typename T>
struct TypeInfo<std::unique_ptr<T>> {
static constexpr const char* name = "unique pointer";
};
Guidelines
- Prefer overloads or concepts first when behavior differs by operation.
- Use specialization when behavior differs by type representation.
- Keep specializations close to the primary template for readability.
[!TIP] Full specialization matches one exact type. Partial specialization matches a family of types.