How do you legally specialize std::hash for your own CacheKey type in C++, and which specializations in namespace std are off limits?
answer
- permission is the exception, not the rule
- must involve a program-defined type
- class templates yes, function templates no
- meet the original template's requirements
basics
~20 sAdding to namespace std is undefined unless permitted. Specializing a standard class template such as std::hash for your CacheKey is allowed if it meets std::hash's requirements; specializing std function templates, type traits, or std::hash for library-only types is not.
solid answer
~50 sThe rule starts with a ban: adding declarations or definitions to `namespace std` is undefined behaviour unless the standard says otherwise. The main exception lets a program add a specialization of a standard library **class template** when the specialization depends on at least one **program-defined type** and meets the requirements of the original template. So `template<> struct std::hash<CacheKey> { std::size_t operator()(const CacheKey&) const noexcept; };` is fine, provided equal keys hash equal and the type is default constructible, copyable and swappable. Off limits: specializing standard **function templates** such as `std::swap` (allowed before C++20, removed by C++20 — overload in your own namespace instead); specializing the type traits in `<type_traits>`, such as `std::is_integral`; specializing member functions of standard templates; adding deduction guides for standard templates; and specializing for types you do not own, such as `std::hash<std::pair<int, int>>`. Compilers rarely diagnose any of these.
code
cpp · 24 lines#include <cstdio>
#include <functional>
#include <string>
#include <unordered_map>
struct CacheKey { // program-defined type
std::string tenant;
int shard;
bool operator==(const CacheKey&) const = default; // C++20 defaulted comparison
};
template <> // allowed: depends on a program-defined type
struct std::hash<CacheKey> {
std::size_t operator()(const CacheKey& k) const noexcept {
std::size_t h = std::hash<std::string>{}(k.tenant);
return h ^ (std::hash<int>{}(k.shard) + 0x9e3779b9 + (h << 6) + (h >> 2));
}
};
int main() {
std::unordered_map<CacheKey, int> cache; // picks std::hash<CacheKey> by default
cache[{"eu", 3}] = 42;
std::printf("%d %zu\n", cache.at({"eu", 3}), cache.size());
}go deeper
Know that you can make your own type usable as an unordered_map key by specializing std::hash for it, and that it must agree with operator==.
State the rule: namespace std is closed except where permitted, class template specializations are allowed when they depend on a program-defined type and meet the original requirements.
Name what is forbidden — function template specializations since C++20, type traits, member specializations, deduction guides, library-only types — and the replacements: overloads found by ADL and custom hashers.
Set a codebase rule that std customizations live beside the type they serve, and review them as API, since compilers cannot catch violations.
## The default: hands off namespace std The standard's starting point is strict: a program that adds declarations or definitions to `namespace std`, or to a namespace inside it, has **undefined behaviour** unless the standard explicitly permits it. Everything legal in this area is an exception to that rule, so the useful question is never "does it compile?" but "which permission covers it?". ## The permission for class templates A program may add a specialization of any standard library **class template** to `namespace std` provided that: 1. the declaration **depends on at least one program-defined type** — a type your program defines, such as `CacheKey`, not `int` or `std::pair<int, int>`; and 2. the specialization **meets the standard library requirements for the original template**. For `std::hash`, the requirements say an enabled specialization `hash<Key>` must meet the *Cpp17Hash* requirements with `Key` as the argument type, be default constructible, copy assignable and swappable, and give equal hashes for keys that compare equal. Library-provided specializations must not throw; a program-defined one is allowed to, though `noexcept` remains good practice. ```cpp struct CacheKey { std::string tenant; int shard; bool operator==(const CacheKey&) const = default; // C++20 }; template <> struct std::hash<CacheKey> { std::size_t operator()(const CacheKey& k) const noexcept; }; ``` With this in place `std::unordered_map<CacheKey, int>` works without naming a hasher. Writing the specialization inside `namespace std { ... }` is equally valid; the qualified form above avoids reopening the namespace. ## What is off limits | Attempt | Status | What to do instead | |---|---|---| | `std::hash<CacheKey>` | Allowed | — | | `std::hash<std::pair<int, int>>` | Undefined: no program-defined type | Pass your own hasher type to the container | | `std::hash<std::string>` or `std::hash<int>` | Undefined: no program-defined type, and the library already provides one | Pass your own hasher | | Specializing `std::swap` for `CacheKey` | Not permitted since C++20 | A `swap` overload in `CacheKey`'s namespace, found by argument-dependent lookup | | Specializing `std::is_integral<MyInt>` | Undefined: type traits forbid specializations | Your own trait | | A deduction guide for `std::vector` | Undefined | Construct with explicit arguments | | Specializing a member function of `std::vector<CacheKey>` | Undefined | Wrap the container | Before C++20 the standard also allowed specializing standard **function templates** for program-defined types. C++20 removed that permission (paper P0551, recorded in libc++'s C++20 status list): function templates in `std` are meant to be customized through overloads that argument-dependent lookup finds, not specializations. ## Why the compiler will not save you These rules are about undefined behaviour, so mostly nothing is diagnosed, and what is diagnosed depends on how the library spells its own specializations: - With libc++, `template<> struct std::hash<int> { ... };` compiles silently. Its `hash<int>` is the primary template inheriting from a partially specialized internal helper, so a user's explicit specialization quietly replaces it. - libstdc++ defines `hash<int>` as an explicit specialization, so the same line there is a redefinition — read from its `functional_hash.h`, not run here. - `std::hash<std::pair<int, int>>` compiles everywhere today and is still undefined, because it depends on no program-defined type; a future standard or library is free to add its own. ## Partial specializations of std templates The permission covers partial specializations as well, under the same two conditions. A library that owns a class template `Handle<T>` may write `template <class T> struct std::hash<Handle<T>>` — every specialization it produces depends on `Handle`, a program-defined template. The same applies to other class templates the standard invites customizing, such as `std::formatter` for your own types; and some standard templates, such as the type traits, opt out explicitly. When a template's own specification states extra rules, those rules win, so read the clause of the template you are customizing, not just the general permission. ## Practical guidance - Specialize `std::hash` only for types you own, in the header that defines the type, so every user sees it before use. - Make it consistent with `operator==`: equal keys must hash equal. - For keys you do not own, write a hasher struct and pass it as the container's `Hash` argument. - For `swap`, write a non-member overload in your namespace. ## Why interviewers ask Specializing `std::hash` is the everyday case of specializing someone else's template. Knowing the permission, its two conditions and the C++20 change for function templates separates candidates who have read the rules from those who rely on "it compiled".
- Why is std::hash<std::pair<int, int>> undefined behaviour even though it compiles and no library provides it?The permission to specialize a standard class template requires the specialization to depend on at least one program-defined type. `std::pair<int, int>` is built entirely from standard types, so nothing in it is yours, and a later library version may add its own specialization. Pass a custom hasher struct to `std::unordered_map` instead.
- How do you customize swap for CacheKey now that specializing std::swap is not allowed?Declare a non-member `void swap(CacheKey&, CacheKey&) noexcept` in the namespace that defines `CacheKey`, or as a hidden friend. Generic code calls it with `using std::swap; swap(a, b);`, so argument-dependent lookup finds your overload and falls back to `std::swap` for other types. Since C++20 this overload is the supported customization; the old function template specialization is not.
- Anything compiles in namespace std, so anything placed there is allowed.
- Specializing std::swap for your type is the recommended customization in C++20.
- std::hash<std::pair<int, int>> is fine because the library does not provide one.
- You may specialize std::is_integral to make your number type count as integral.
- A std::hash specialization only needs operator(); its other requirements do not matter.
Assumes C++23 wording; C++20 removed the permission to specialize standard function templates such as std::swap.