skip to content

Full and Partial Specialization

A full specialization replaces a template for one argument set, a partial one for a pattern, and function templates allow only full ones. Interviewers ask why overloading usually wins.

on this pageshow

explore

questions

4

In C++, how do you write a full specialization Hasher<std::string> of a class template, and what does it keep from the primary template?

level: juniorimportance: should knowfreq 55%

answer

  1. empty angle brackets after template
  2. a brand-new class for one argument
  3. members are not inherited
  4. declare it before first use

basics

~20 s

Write template<> struct Hasherstd::string { ... }; after the primary template is declared. It is a completely separate class used whenever the argument is exactly std::string; it inherits no members from the primary, so everything it needs must be redeclared.

solid answer

~50 s

A full (explicit) specialization starts with `template<>` and names every template argument: `template<> struct Hasher<std::string> { std::size_t operator()(const std::string&) const; };`. The primary template must be declared first. From then on, every use of `Hasher<std::string>` gets this class instead of one generated from the primary. It keeps nothing from the primary template — not its data members, not its member functions, not its static constants — because the standard says its definition is unrelated to a generated specialization; it only has to have the same name and argument list. So if the primary declares `static constexpr const char* name`, `Hasher<std::string>::name` does not exist unless you write it again. It must also be declared before any use that would implicitly instantiate `Hasher<std::string>` from the primary; clang reports `explicit specialization of 'Hasher<std::string>' after instantiation` when the order is wrong in one file.

code

cpp · 23 lines
cpp
#include <cstdint>
#include <cstdio>
#include <functional>
#include <string>

template <class T> struct Hasher {                 // primary template
    static constexpr const char* name = "generic";
    std::size_t operator()(const T& v) const { return std::hash<T>{}(v); }
};

template <> struct Hasher<std::string> {           // full (explicit) specialization
    std::size_t operator()(const std::string& s) const {   // FNV-1a over the bytes
        std::uint64_t h = 14695981039346656037ull;
        for (unsigned char c : s) { h ^= c; h *= 1099511628211ull; }
        return static_cast<std::size_t>(h);
    }
};

int main() {
    std::printf("%s\n", Hasher<int>::name);
    std::printf("%d\n", Hasher<std::string>{}("key") == Hasher<std::string>{}(std::string("key")));
    // Hasher<std::string>::name;   // error: no member named 'name' -- nothing is inherited
}

go deeper

for a junior

Know the syntax template<> struct Hasherstd::string { ... } and that it replaces the generated class for exactly that argument.

for a middle

Explain that the specialization shares nothing with the primary, that it must be declared after the primary and before first use, and how to define its members out of class without template<>.

for a senior

Spot the multi-file trap where one translation unit uses the generic version because it never saw the specialization, and keep specializations in the primary's header.

for a principal

Decide when a library should invite users to specialize its templates and how to document the interface a specialization must keep.

## What a full specialization is A **class template** such as `template <class T> struct Hasher` describes a family of classes. Normally the compiler generates `Hasher<int>`, `Hasher<double>` and so on from that one **primary template**. A **full specialization** — the standard calls it an **explicit specialization** — replaces the generated class for one exact argument list with a class you write by hand. The syntax is `template<>` followed by the class with all its arguments filled in: ```cpp template <class T> struct Hasher { // primary template static constexpr const char* name = "generic"; std::size_t operator()(const T& v) const { return std::hash<T>{}(v); } }; template <> struct Hasher<std::string> { // full specialization std::size_t operator()(const std::string& s) const; // e.g. FNV-1a over the bytes }; ``` The empty `<>` says no template parameters remain: every argument is fixed. ## What it keeps and what it does not The rule in the standard is blunt: the definition of an explicitly specialized class is unrelated to the definition of a generated one. In practice: - **Nothing is inherited.** `Hasher<std::string>` has no `name` member, even though the primary has one. Clang answers `Hasher<std::string>::name` with `no member named 'name' in 'Hasher<std::string>'`. - **The interface may differ completely.** A specialization may add, drop or change members, constructors and base classes. `std::vector<bool>` — a partial specialization, `vector<bool, Allocator>` — is the famous standard example of a specialization with a different interface. - **Only the name and arguments tie it to the primary.** Code written against the primary's interface compiles for the specialization only if you kept the members it uses. - **Members are defined like a normal class's.** An out-of-class member definition of a fully specialized class does not repeat `template<>`: `std::size_t Hasher<std::string>::operator()(const std::string& s) const { ... }`. Because nothing is shared, a common pattern is to move the shared parts into a base class that both the primary and the specializations derive from, and specialize only the part that differs. ## Ordering rules Two ordering rules matter: 1. **The primary template must be declared first.** A declaration is enough; its definition is not needed. `template<> struct X<int> {};` before any `template<class T> struct X;` is an error because `X` is not yet a template. 2. **The specialization must be declared before any use that would instantiate the primary for those arguments**, in every translation unit with such a use. Otherwise the program is ill-formed, no diagnostic required. Within one file clang does diagnose it: ```plaintext error: explicit specialization of 'Hasher<std::string>' after instantiation note: implicit instantiation first required here ``` Across files no compiler can see it: one file that forgot to include the specialization's header silently uses the generic `Hasher<std::string>`, while another uses the hand-written one. Put the specialization in the same header as the primary, or in a header the primary's header includes. ## Where to put it | Kind | Place | Why | |---|---|---| | Class template full specialization | Same header as the primary, right after it | Every user must see it before use | | Member functions defined out of class | Header with `inline`, or one `.cpp` | They are ordinary member functions now | | Full specialization of a function template | Header with `inline`, or declared in the header and defined in one `.cpp` | It is an ordinary function, not a template | The last row catches people: a full specialization of a function template is a normal function, so defining it in a header without `inline` breaks the one-definition rule once two files include it. ## When to reach for it - A type needs a different algorithm: hashing the bytes of a `std::string` with FNV-1a instead of the generic path. - A type needs a different representation: packing bits, as the standard's `vector<bool, Allocator>` partial specialization does. - A customization point invites it: the standard library lets programs specialize some class templates, such as `std::hash`, for their own types. For a family of types — all pointers, all `std::vector`s — a full specialization per type does not scale; that is what partial specialization is for. ## Why interviewers ask The syntax is easy; the follow-ups are not. Interviewers check that you know a specialization is a separate class that must re-provide its interface, and that a specialization declared too late or in the wrong header silently splits the program into two behaviours.

  • Can you specialize just one member function of Hasher for std::string instead of the whole class?
    Yes. `template<> std::size_t Hasher<std::string>::operator()(const std::string& s) const { ... }` explicitly specializes that member for the implicitly instantiated `Hasher<std::string>`, keeping every other member from the primary. The primary's class definition must be visible, and the same before-first-use rule applies. It is the lighter tool when only one behaviour differs.
  • How do you share code between the primary Hasher and its specializations?
    Put the shared members in a non-template or template base class, say `HasherBase`, and have both the primary and each specialization derive from it. The specialization then writes only what differs. Without a base, every specialization must re-declare everything callers use, and the copies drift apart over time.

  • A full specialization inherits the primary's members and only overrides what it redefines.
  • A full specialization can be declared before the primary template.
  • Declaring the specialization in a .cpp file after other files used the type is fine.
  • template<> is optional when the argument list is already complete.
  • Members of a fully specialized class are defined with template<> in front.
open as a page

How do you legally specialize std::hash for your own CacheKey type in C++, and which specializations in namespace std are off limits?

level: middleimportance: should knowfreq 55%

basics

~20 s

Adding 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.

open as a page

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%

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.

open as a page

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?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A 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.

open as a page