5.2.15C++ Programming

Template specialization — full and partial

2,035 words9 min readdifficulty · medium1 backlinks

WHY does specialization exist?


WHAT are the three things to distinguish?


HOW to write each — derived from first principles

Step 1 — The primary template

template<class T>
struct TypeName {
    static const char* name() { return "generic"; }
};

Why this step? This is the fallback. Anything not specialized lands here.

Step 2 — Full specialization (ALL params concrete)

template<>                    // empty <> = "no free parameters left"
struct TypeName<int> {        // <int> = the exact type we override for
    static const char* name() { return "int"; }
};

Why template<>? You filled in every parameter, so zero parameters remain — the angle brackets are empty. The <int> after the name says which instantiation you're replacing.

Step 3 — Partial specialization (SOME params / a shape)

template<class T>             // T is still free
struct TypeName<T*> {         // but we matched the SHAPE "pointer to T"
    static const char* name() { return "pointer"; }
};
 
template<class A, class B>
struct TypeName<pair<A,B>> {  // matches ANY pair, A and B still free
    static const char* name() { return "pair"; }
};

Why is this "partial"? You haven't pinned the type to one concrete thing — you've pinned its structure while leaving T (or A,B) open. So it covers a whole family.

Figure — Template specialization — full and partial

The selection rule (the heart of it)


Worked Examples



Flashcards

What keyword sequence begins a FULL specialization?
template<> (empty angle brackets — zero free parameters remain).
Full vs partial specialization in one line each?
Full = all template params fixed to concrete types; partial = some params fixed OR the shape constrained, with params still free.
Can function templates be PARTIALLY specialized?
No — only fully. Use overloading for partial-like behaviour.
For type int*, which wins: primary T or partial T*?
T* — it is more specialized (matches a strict subset of T).
When does the compiler report an ambiguity among specializations?
When two partial specializations match but neither is more specialized than the other.
Where must a specialization be declared relative to first use?
Before the type's first instantiation, and in the same namespace as the primary.
What real STL feature is built using partial specialization?
Type traits like std::is_pointer, and std::vector<bool> (full-ish container specialization).
Why does std::vector<bool> differ from std::vector<int>?
It's a specialization that bit-packs booleans to save space, so it doesn't store real bool objects.
What is "partial ordering" of specializations?
The rule that says spec A is more specialized than B if every type matching A also matches B but not conversely.
Can a partial specialization add a NEW default template argument?
No — default template arguments belong only on the primary template.

Recall Feynman: explain it to a 12-year-old

Imagine a vending machine that makes a sandwich for any filling you ask for — that's the generic template. But for peanut butter, you have a secret special recipe (add jelly!) — that's a full specialization: it only triggers for that exact filling. Now suppose for anything that comes in a tin can you want to open it first — that's a partial specialization: it doesn't care what's in the can, just that it's "can-shaped." When you press a button, the machine checks: is there an exact special recipe? Use it. Otherwise, does any "shape" recipe fit? Use the most specific one. Otherwise, use the boring generic recipe.


Connections

  • Templates — function and class basics
  • Type Traits and std::is_pointer
  • SFINAE and enable_if
  • Overload Resolution vs Specialization
  • std::vector<bool> special case
  • Tag Dispatch and Policy-based Design
  • constexpr if (C++17) — alternative to specialization

Concept Map

fails for some types

motivates

same name swap impl

is the

fallback for

fix ALL params

fix SOME or shape

written as

keeps free params

matches shapes like

only kind allowed for

forbidden on functions use

Generic template recipe

Wrong slow or impossible

Specialization

Caller never notices

Primary template

Unspecialized types

Full specialization

Partial specialization

template empty brackets

template with remaining T

T-pointer or pair A B

Function templates

Overloading instead

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, template ek generic recipe hoti hai — template<class T> likhke tum compiler ko bolte ho "kisi bhi type ke liye yeh code bana do." Par kabhi-kabhi kisi khaas type ke liye yeh generic code galat ya slow hota hai. Tab specialization kaam aata hai: same naam, same interface, lekin andar ka implementation badal do us special case ke liye. Caller ko pata bhi nahi chalta.

Do flavours hote hain. Full specialization matlab saare template parameters ko ek exact concrete type se fix kar do — syntax hota hai template<> (khaali brackets, kyunki koi free parameter bacha hi nahi) aur naam ke aage <int> jaisa exact type. Partial specialization matlab saare nahi, sirf kuch parameters fix karo ya type ki shape match karo — jaise T* (koi bhi pointer) ya pair<A,B> (koi bhi pair). Yahan kuch parameters abhi bhi free rehte hain, isliye "partial."

Compiler kaise choose karta hai? Pehle dekhega koi exact full spec hai kya — agar haan to wahi. Phir jo partial specs match karte hain unme se sabse specialized (sabse narrow pattern) wala jeetta hai. Agar do partial barabar match karte hain aur koi ek dusre se zyada specific nahi, to ambiguity error. Agar kuch bhi special match na ho, to plain generic primary chalega.

Ek important catch yaad rakhna: functions ko sirf FULL specialize kar sakte ho, partial nahi — uske liye overloading use karte hain. Aur full spec pe template<> lagana mat bhoolna, warna compiler samjhega tum primary ko dobara declare kar rahe ho. Yeh concept real STL me bahut use hota hai — jaise std::is_pointer partial spec se bana hai aur std::vector<bool> ek special bit-packed version hai. Isiliye yeh 80/20 wala topic hai: thoda samjho, bahut jagah kaam aata hai.

Go deeper — visual, from zero

Test yourself — C++ Programming

Connections