skip to content

Why can't you partially specialize a C++ function template like hash_value<T*>, and why does overloading usually beat full specialization for function templates?

level: seniorimportance: should knowfreq 45%

answer

  1. the grammar wants a plain name
  2. overloads already give the pattern
  3. specializations skip overload resolution
  4. which base template did it specialize

basics

~20 s

C++ forbids partial specialization of function templates; overloading does that job. A full specialization takes no part in overload resolution: the compiler picks a primary template first and only then uses its specializations, so one can be silently bypassed.

solid answer

~50 s

In a function template declaration the name must be a plain name, so `template<class T> std::size_t hash_value<T*>(T*)` is rejected — clang says `function template partial specialization is not allowed`. You write an overload instead: `template<class T> std::size_t hash_value(T*)`. Full specializations (`template<> ... hash_value<int*>(int*)`) are allowed but behave surprisingly. Overload resolution considers only **primary templates** and non-template functions; a specialization is consulted only after its own primary template has won. A specialization belongs to the primary template that is the best match at the point where it is declared. Declare `hash_value<int*>` after only `hash_value(T)` exists and it specializes that one; add the `hash_value(T*)` overload later and calls with `int*` pick the overload, so the specialization is never called. Declared after the overload, it specializes the overload and works. A plain non-template overload, `std::size_t hash_value(int*)`, avoids all of this: it takes part in overload resolution and wins ties against templates.

code

cpp · 11 lines
cpp
#include <cstdio>

template <class T> const char* hash_kind(T)  { return "(a) base T"; }      // (a)
template <> const char* hash_kind<int*>(int*) { return "(c) full spec of (a)"; }  // (c): only (a) exists yet
template <class T> const char* hash_kind(T*) { return "(b) overload T*"; }  // (b)

int main() {
    int x = 0;
    std::printf("%s\n", hash_kind(&x));   // overload resolution picks (b); (c) is never considered
    std::printf("%s\n", hash_kind(1.5));  // (a)
}

go deeper

for a junior

Know that function templates cannot be partially specialized and that you write another overload, such as hash_value(T*), instead.

for a middle

Explain that overload resolution chooses among primary templates and non-templates first, and only then uses an explicit specialization of the winner.

for a senior

Demonstrate the declaration-order trap where a specialization attaches to the wrong primary and is never called, and recommend non-template overloads or forwarding to a class template.

for a principal

Choose the customization mechanism a library exposes, overloads found by lookup or class template specializations, and document it so users never specialize function templates.

## Function templates cannot be partially specialized Class templates have partial specialization; function templates do not. The rule is in the grammar: in a function template declaration, the declarator's name must be a plain name, not a *template-id* such as `hash_value<T*>`. Clang 21 is explicit: ```plaintext error: function template partial specialization is not allowed ``` The language does not need it, because **overloading** already lets you write a function template for a pattern: ```cpp template <class T> std::size_t hash_value(T v); // (a) any type template <class T> std::size_t hash_value(T* p); // (b) any pointer: an overload, not a specialization ``` Overload resolution, with partial ordering of function templates as a tie-breaker, picks `(b)` for pointer arguments because it is more specialized. ## How a call is resolved For `hash_value(&x)` with `x` an `int`: 1. Deduction runs for each **primary** function template — `(a)` and `(b)` — producing candidates `hash_value<int*>(int*)` from `(a)` and `hash_value<int>(int*)` from `(b)`. 2. Non-template functions with the name are added. 3. Overload resolution picks the best; between equally good templates, partial ordering prefers `(b)`. 4. **Only now** does the compiler check whether the chosen template has an explicit specialization for the deduced arguments. If it has, that body runs. Explicit specializations never appear in step 1. They are not overloads; they are alternative bodies for one specialization of one primary template. ## Which template does a specialization belong to? `template<> std::size_t hash_value<>(int*)` must name a specialization of some primary template, chosen by the same deduction and ordering rules **among the primaries visible at that point**: - Declared when only `(a)` exists, it can only be `(a)` with `T = int*`. - Declared after `(b)`, it matches both, and `(b)` is more specialized, so it specializes `(b)` with `T = int`. That produces the well-known trap: ```cpp template <class T> const char* hash_kind(T) { return "(a) base T"; } template <> const char* hash_kind<int*>(int*) { return "(c) full spec of (a)"; } template <class T> const char* hash_kind(T*) { return "(b) overload T*"; } int x = 0; hash_kind(&x); // prints "(b) overload T*": (c) belongs to (a), and (a) lost ``` Moving `(c)` below `(b)` makes the same call print `(c)`. Nothing in the source near the call reveals which applies; it depends on declaration order in the header. ## Specialize or overload? | Need | Tool | Why | |---|---|---| | One exact type, function template | Non-template overload `hash_value(int*)` | Takes part in overload resolution and beats an equally good template | | A family of types, function template | Overloaded function template `hash_value(T*)` | The only way to express a pattern | | A family of types with shared state or members | Class template partial specialization, called from a function template | Class templates support partial specialization | | One exact type, class template | Full specialization | The class is chosen by its arguments, not by overload resolution | A common design delegates: the function template forwards to a class template, `Hasher<T>{}(v)`, so customizers specialize the class — fully or partially — and never meet the overload-versus-specialization trap. ## Reading the trap in a real header The declaration-order trap rarely looks like three adjacent lines. More often a library header declares the generic `hash_value(T)` and a specialization for `int*`, and a later header — perhaps written by another team — adds the pointer overload. Every file that includes both headers silently stops calling the specialization. Nothing warns: both declarations are valid, and the program still hashes `int*` values, just with the generic pointer overload's algorithm. Tests that include only the first header keep passing. This is why reviewers treat any explicit specialization of a function template in a shared header as a smell. ## Other differences - **Default arguments** cannot be given in an explicit specialization of a function template; the primary's are used. - **Linkage:** a full specialization is an ordinary function, so one defined in a header needs `inline`. - **Explicit template arguments:** a call such as `hash_value<int*>(&x)` names a specialization of `(a)` directly and runs `(c)` in the trap above — another way the two forms diverge. ## Why interviewers ask "Why not specialize function templates?" is a classic senior question. A strong answer names the missing partial specialization, explains that specializations do not overload, demonstrates the declaration-order trap, and recommends overloads or a class template to customize.

  • What does hash_kind<int*>(&x) print in the trap version, where the specialization was declared before the T* overload?
    It prints the specialization's text. With `<int*>` given explicitly, overload `(b)` would need `T*` to be `int**`, which does not match `int*`, so only `(a)` with `T = int*` is viable. That is exactly the specialization `(c)` belongs to, so `(c)` runs. The same function called with and without explicit arguments takes different bodies.
  • Why do many libraries make a function template call a class template instead of letting users specialize the function?
    A class template can be partially specialized, its selection depends only on its arguments, and the most specialized match wins regardless of declaration order relative to other partial specializations. So users can customize a family of types reliably. The function template stays a thin forwarding layer, as `std::hash` sits behind the unordered containers' calls.

  • template<class T> void f<T*>(T*) is a valid partial specialization.
  • An explicit specialization of a function template is an overload that wins exact matches.
  • Declaration order never matters for function template specializations.
  • A non-template overload loses to an equally good template specialization.
  • Function template specializations take part in overload resolution alongside overloads.