Specialization, overloading, and customization points
This chapter presents the decision rule for choosing concepts versus specialization, then shows the related mechanisms.
Class template specialization
A class template defines a family of types parameterised by one or more template arguments. A full specialization provides a concrete definition for a specific set of arguments. A partial specialization fixes some arguments while leaving others as parameters.
// Primary template: works for any type T
template <typename T>
struct Printer {
static void print() { std::cout << "primary" << '\n'; }
};
// Partial specialization for pointer types
template <typename T>
struct Printer<T*> {
static void print() { std::cout << "pointer" << '\n'; }
};
The primary template is selected when the argument list does not match any partial or full specialization. The partial specialization above matches any pointer type T*. The compiler chooses the most specialised viable definition.
#include <iostream>
// Primary template
template <typename T>
struct Printer {
static void print() {
std::cout << "primary\n";
}
};
// Partial specialization for pointer types
template <typename T>
struct Printer<T*> {
static void print() {
std::cout << "pointer\n";
}
};
int main() {
Printer<int>::print(); // prints "primary"
Printer<int*>::print(); // prints "pointer"
return 0;
}
How the compiler decides
- Matching: the argument list is compared against each specialization’s pattern.
- Partial ordering: if more than one specialization matches, the compiler ranks them by how many arguments are fixed. The one with the greater number of fixed arguments is preferred.
- Full specialization: a specialization that fixes all arguments is the ultimate match and overrides any partial specialization.
Because specializations are an out‑of‑band mechanism, they do not participate in overload resolution. They merely replace the primary definition before the compiler instantiates the class template.
A full specialization is written with an empty template parameter list and a concrete argument: template<> struct Printer<int> { ... };. It is the only form that can introduce a definition with a completely different set of members, because it no longer depends on any template parameter. Partial specializations must still match the primary template’s parameter list in shape, so they can vary the pattern but not the member set arbitrarily. In practice most code needs at most one partial specialization and a handful of full ones.
One caution: the primary template must remain well formed even if only specializations are used, because the compiler instantiates the primary in some contexts before consulting specializations. Keep a sensible default body in the primary and treat specializations as refinements.
The decision rule
When you need different behaviour, ask two questions:
- Do the types share the same logical interface? If the answer is yes but the implementation varies based on a property (e.g., pointer vs non‑pointer), prefer concepts or
if constexprinside a generic implementation. - Is the representation fundamentally different? If the answer is no but the underlying storage or layout differs (e.g., a raw array versus a
std::span), use specialization.
In short, choice is semantic → use concepts. Representation changes → specialise.
Applying the decision rule consistently avoids scattered overloads and specializations. When a concept describes a semantic property, the requirement appears directly in the function signature and the implementation stays in a single generic body. Use specialization only when the type’s layout or representation differs fundamentally, such as a raw array versus a std::span. This discipline simplifies refactoring and provides clearer compile‑time diagnostics.
Variable templates
Variable templates let you define compile‑time constants that depend on a template parameter. They are the value‑side analogue of function templates.
template <typename T>
constexpr T pi = static_cast<T>(3.1415926535897932385L);
static_assert(pi<double> == 3.1415926535897932385);
The standard library uses this pattern extensively, e.g. the _v suffix for trait variables such as std::is_same_v<T, U>.
#include <type_traits>
#include <iostream>
template <typename T>
constexpr T pi = static_cast<T>(3.1415926535897932385L);
int main() {
static_assert(pi<double> == 3.1415926535897932385);
std::cout << "pi<double> = " << pi<double> << '\n';
return 0;
}
Variable templates are instantiated only when ODR‑used, so they impose no runtime cost. They also serve as a natural place for configuration constants such as std::numeric_limits<T>::max(). They compose, e.g., template<typename T> constexpr T half_pi = pi<T> / 2;, allowing the compiler to fold arithmetic at translation time. Because they are constexpr, they can feed static_assert, if constexpr conditions, or non‑type template arguments, bridging value and type worlds. Variable templates also act as value‑side customization points. A library can declare template<typename T> struct traits; and specialize traits<T>::value, while a variable template like template<typename T> inline constexpr bool is_trivially_copyable_v provides the standard‑preferred concise spelling.
if constexpr as in‑body dispatch
Sometimes a single function needs two completely different implementations, but you do not want to write separate overloads or specializations. if constexpr lets you branch at compile time based on a constant expression.
template <typename T>
void show() {
if constexpr (std::is_pointer_v<T>) {
std::cout << "pointer" << '\n';
} else {
std::cout << "primary" << '\n';
}
}
int main() { show<int*>(); show<int>(); }
The compiler discards the unreachable branch, so no ill‑formed code can appear in the omitted path. This technique is especially useful when the two paths require different headers or heavy SFINAE tricks.
#include <type_traits>
#include <iostream>
template <typename T>
void show() {
if constexpr (std::is_pointer_v<T>) {
std::cout << "pointer" << '\n';
} else {
std::cout << "primary" << '\n';
}
}
int main() {
show<int*>();
show<int>();
return 0;
}
if constexpr replaces tag dispatch. The compiler discards the unreachable branch, so the same show function works for both pointer and non‑pointer arguments without any overload set.
Specialising std::formatter
std::format formats arbitrary types using the formatter customization point. To make a user‑defined type printable, you specialise std::formatter<T> for your type T.
struct Vec2 { int x, y; };
template <> struct std::formatter<Vec2> : std::formatter<std::string> {
// parse format spec - we ignore it for simplicity
constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
// format the value
auto format(const Vec2& v, format_context& ctx) const {
return std::format_to(ctx.out(), "({},{})", v.x, v.y);
}
};
int main() {
Vec2 v{3,4};
std::cout << std::format("Vec2: {}", v) << '\n';
}
The specialization lives in the same namespace as std (the only exception allowed by the standard). It enables the type to be used with std::format, std::print, and any other formatting facility that forwards to the std::formatter trait.
#include <format>
#include <iostream>
struct Vec2 { int x, y; };
template <> struct std::formatter<Vec2> : std::formatter<std::string> {
// No format specifiers – ignore the parse context
constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
auto format(const Vec2& v, std::format_context& ctx) const {
return std::format_to(ctx.out(), "({},{})", v.x, v.y);
}
};
int main() {
Vec2 v{3,4};
std::cout << std::format("Vec2: {}", v) << '\n';
return 0;
}
Why specialise instead of overloading?
Overloading operator<< works only for stream‑based APIs. std::format follows a type‑centric design: the formatter is a customisation point object (CPO) that the library calls. By providing a specialization, you integrate with the whole formatting ecosystem without pulling in iostreams.
The parse member decodes the part of the format string that follows the colon, and format writes the value. Inheriting from an existing formatter such as std::formatter<std::string> is a shortcut when you want default spec handling. For a type with no natural spec, parse just returns the begin iterator. The specialization must be visible in the namespace of the type or of std, which is why the standard permits specialising std::formatter for user types even though it otherwise forbids adding to std.
Specialising std::hash
std::unordered_map and std::unordered_set hash their keys through std::hash<Key>. A user type has no default, so to use one as a key you specialise std::hash:
struct Key { int id; std::string name; };
template <>
struct std::hash<Key> {
std::size_t operator()(const Key& k) const noexcept {
std::size_t h1 = std::hash<int>{}(k.id);
std::size_t h2 = std::hash<std::string>{}(k.name);
return h1 ^ (h2 << 1);
}
};
The specialization must be a complete type with an operator() returning std::size_t. Combine the hashes of the members with a shift and XOR so the result depends on both fields. Equality must stay consistent with the hash: two keys that compare equal must hash equal, or the container misbehaves. The same pattern powers the customization that std::unordered_map relies on for every key type.
Because the hash and the equality operator must agree, define them together. If you change the equality later, update the hash in the same change or lookups return wrong results silently. The standard library also lets you supply a custom hasher or comparator as template arguments to unordered_map, so a bespoke type can avoid touching std::hash entirely when its needs are unusual.
ADL and hidden friends
Argument-dependent lookup (ADL) finds functions in the namespaces of their arguments. When a == b is written, the compiler looks for operator== not only in the enclosing scope but also in the namespaces of a and b. A hidden friend is an operator== defined inside the class body. It is reachable only through ADL, so it never pollutes the global namespace and cannot be called without the right argument types.
struct Point {
int x, y;
friend bool operator==(const Point& a, const Point& b) = default;
};
Because the friend is defined inline, it is a hidden friend and ADL is the only mechanism that finds it. This keeps the operator close to the type, prevents accidental calls on unrelated types, and gives the best diagnostics: a call with a mismatched operand names Point rather than surfacing an unrelated overload. The same reasoning applies to any operator used only with its own operand types.
To summarize, the library can combine concepts, specializations, variable templates, and customization point objects to provide a clear, layered customization strategy that keeps generic code simple and concrete overrides focused.
Try this
Create a small struct Color { uint8_t r,g,b } and write a std::formatter<Color> that formats the colour as a hex string #RRGGBB. Verify the output with std::format.