A C++ caching library defines Hasher<T*>, Hasher<const T*> and Hasher<const char*>: which one does each pointer type use, and when is the choice ambiguous?
answer
- exact full specialization wins first
- then the most specialized match
- rewrite as function templates and deduce
- char* is not const char*
basics
~20 sA full specialization matching exactly wins outright; otherwise the compiler picks the most specialized matching partial specialization. Hasher<const char*> uses its full specialization, const double* uses Hasher<const T*>, char* falls to Hasher<T*>. Two matches with neither more specialized is an error.
solid answer
~50 sFor `Hasher<X>` the compiler first checks for a full specialization with exactly `X`; `Hasher<const char*>` has one, so it wins without any ranking. Otherwise it collects the partial specializations whose pattern matches `X` by deduction. One match is used; none means the primary. With several, it uses **partial ordering**: each partial specialization is rewritten as a function template taking its pattern, and one is more specialized if its pattern can be deduced from the other's but not the reverse. For `const double*`, both `T*` (with `T = const double`) and `const T*` match; `const T*` is more specialized, so it is used. `char*` matches only `T*` — so a mutable C string is hashed by address, a real cache bug. When neither match is more specialized, such as `Hasher<std::pair<A*, B>>` and `Hasher<std::pair<A, B*>>` for `std::pair<int*, int*>`, clang reports `ambiguous partial specializations`.
code
cpp · 31 lines#include <cstdio>
#include <cstring>
#include <functional>
#include <string_view>
template <class T> struct Hasher { // #1 primary
static constexpr const char* which = "primary";
};
template <class T> struct Hasher<T*> { // #2 any pointer: hash the address
static constexpr const char* which = "T*";
std::size_t operator()(T* p) const { return std::hash<T*>{}(p); }
};
template <class T> struct Hasher<const T*> { // #3 pointer to const
static constexpr const char* which = "const T*";
};
template <> struct Hasher<const char*> { // #4 C string: hash the characters
static constexpr const char* which = "const char*";
std::size_t operator()(const char* s) const {
return std::hash<std::string_view>{}(std::string_view(s, std::strlen(s)));
}
};
int main() {
std::printf("%s\n", Hasher<int>::which); // primary
std::printf("%s\n", Hasher<double*>::which); // T* (only #2 matches)
std::printf("%s\n", Hasher<const double*>::which);// const T* (#2 and #3 match, #3 is more specialized)
std::printf("%s\n", Hasher<const char*>::which); // const char* (full specialization wins outright)
std::printf("%s\n", Hasher<char*>::which); // T*: a mutable C string still hashes its address
char a[] = "key", b[] = "key";
std::printf("%d\n", Hasher<const char*>{}(a) == Hasher<const char*>{}(b)); // 1: same text
}go deeper
Know that template<class T> struct Hasher<T*> covers every pointer type and that a full specialization for one exact type takes priority.
Walk through the procedure: exact full specialization, matching partial specializations, the primary when none match, and the most specialized when several do.
Explain partial ordering by deduction, predict const T* over T*, catch the char* versus const char* hashing bug, and fix an ambiguity with an overlap specialization.
Keep a specialization set small enough that its winners can be predicted, and test the edge types a cache will really see.
## Partial specialization in one paragraph A **partial specialization** keeps some template parameters and fixes a pattern: `template <class T> struct Hasher<T*>` applies to every pointer type, with `T` deduced from the argument. Only class templates and variable templates can be partially specialized. A caching library uses them to give whole families of key types their own hashing policy while the primary handles everything else. ## The selection procedure For a use such as `Hasher<X>`, the compiler decides which definition to instantiate: 1. **Full specialization for exactly `X`?** If `template<> struct Hasher<X>` exists, it is used. It is not ranked against partial specializations; it simply is the class for that argument. 2. **Match the partial specializations.** A partial specialization matches if its pattern's parameters can be deduced from `X`, and its constraints, if any, are satisfied. 3. **Exactly one match:** use it. **None:** use the primary template. 4. **Several matches:** apply **partial ordering**. If one is more specialized than all the others, use it; otherwise the use is ambiguous and the program is ill-formed. ## How "more specialized" is decided The standard reduces the question to function templates. Each partial specialization becomes an imaginary function template taking its pattern as a parameter: - `Hasher<T*>` becomes `template<class T> void f(Hasher<T*>)` - `Hasher<const T*>` becomes `template<class T> void f(Hasher<const T*>)` Then it tries deduction both ways with invented unique types: - From the `const U*` pattern, deducing `T*` works with `T = const U`. - From the `U*` pattern, deducing `const T*` fails: `U*` is not necessarily a pointer to `const`. So `Hasher<const T*>` accepts a strict subset of what `Hasher<T*>` accepts and is **more specialized**. ## The caching library's table | Use | Matches | Chosen | Effect | |---|---|---|---| | `Hasher<int>` | none | primary | generic hash | | `Hasher<double*>` | `T*` | `T*` | hashes the address | | `Hasher<const double*>` | `T*`, `const T*` | `const T*` | more specialized wins | | `Hasher<const char*>` | full specialization | `Hasher<const char*>` | hashes the characters | | `Hasher<char*>` | `T*` | `T*` | hashes the address | The last row is a real cache bug. A key stored as `char*` gets `Hasher<T*>`, so two buffers holding `"key"` at different addresses produce different hashes, and lookups miss. The full specialization covers exactly `const char*`; `char*` is a different type. Either add `Hasher<char*>` or normalize keys to `std::string_view` before hashing. The standard's own `std::hash` has the same property: it is enabled for every pointer type, and since equal pointer values are what compare equal, `std::hash<const char*>` hashes the pointer, never the text. ## Ambiguity With two parameters, patterns can overlap without either containing the other: ```cpp template <class A, class B> struct Hasher<std::pair<A*, B>> {}; template <class A, class B> struct Hasher<std::pair<A, B*>> {}; Hasher<std::pair<int*, int*>> h; // both match, neither is more specialized ``` Clang 21 rejects it: ```plaintext error: ambiguous partial specializations of 'Hasher<std::pair<int *, int *>>' note: partial specialization matches [with A = int, B = int *] note: partial specialization matches [with A = int *, B = int] ``` The fix is to add a third specialization for the overlap, `Hasher<std::pair<A*, B*>>`, which is more specialized than both. Adding it is a one-line change, but it is easy to miss in review: the ambiguity appears only when someone first uses a pair of two pointers, possibly long after both specializations shipped. ## Other rules worth knowing - **A partial specialization must be reachable before any use that would need it**, or the program is ill-formed, no diagnostic required — the same split-behaviour risk as with full specializations. - **Every parameter must be deducible from the pattern.** `template<int I> struct A<I + 5, I * 2>` is ill-formed because `I` cannot be deduced. - **Members are not shared.** Like a full specialization, a partial specialization is a separate class template with its own members. - **Constraints can order them too.** Since C++20 a constrained partial specialization can be preferred because it is more constrained; that machinery belongs with concepts. ## Why interviewers ask Predicting which specialization a type picks is the core skill. The const-pointer row and the `char*` miss show whether a candidate reasons about the exact type rather than about "strings" and "pointers" in general.
- How do you resolve the ambiguity between Hasher<std::pair<A*, B>> and Hasher<std::pair<A, B*>>?Add a partial specialization for the overlap, `template<class A, class B> struct Hasher<std::pair<A*, B*>>`. It matches `std::pair<int*, int*>` too, and its pattern can be deduced from each of the other two while neither of theirs can be deduced from it, so it is more specialized than both and wins. Alternatively restructure so only one specialization handles pairs.
- Would Hasher<int* const> use Hasher<T*>?No. The template argument `int* const` is a const-qualified pointer type, and the pattern `T*` does not match a top-level const, so the primary template is used. Template arguments keep their cv-qualifiers, unlike function arguments passed by value. Strip them before naming the hasher, for example with `std::remove_cv_t`, if the library should treat both alike.
- The partial specialization declared last is the one the compiler picks.
- Hasher<const char*> covers char* keys as well.
- When two partial specializations match, the compiler silently uses the primary.
- A full specialization competes in partial ordering like any partial specialization.
- Function templates can be partially specialized with the same ordering rules.