C++ · Module 12 · Lesson 31 min read

Template Specialization

Full (explicit) specialization

Provide a completely different implementation for one specific type:

c
template <typename T>
std::string describe(const T& x) { return "value: " + std::to_string(x); }

template <>
std::string describe<bool>(const bool& x) { return x ? "yes" : "no"; }

For functions, a plain overload is often simpler and preferred.

Class template specialization

perl
template <typename T>
class Formatter { public: std::string format(const T& v); };

template <>
class Formatter<bool> { public: std::string format(bool v) { return v ? "true" : "false"; } };

The specialization is a whole new class — it can have different members.

Partial specialization (classes only)

Specialize for a family of types:

perl
template <typename T> class Formatter<T*>       { ... };   // any pointer
template <typename T> class Formatter<std::vector<T>> { ... };   // any vector

Functions can't be partially specialized — use overloading instead.

if constexpr (C++17) — often simpler ✅

Branch on types at compile time inside one template:

c
template <typename T>
std::string to_text(const T& v) {
    if constexpr (std::is_same_v<T, bool>) return v ? "yes" : "no";
    else if constexpr (std::is_arithmetic_v<T>) return std::to_string(v);
    else return std::string(v);
}

Discarded branches aren't instantiated, so they don't need to compile for that T.

Real examples in the standard library

  • std::vector<bool> is a (controversial) specialization that packs bits
  • std::hash<T> is specialized for each hashable type — you specialize it for your own types to use them in unordered_map (Unit 13)
  • std::numeric_limits<T> is specialized for each numeric type

Example

C++
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

// Primary class template
template <typename T>
struct Formatter {
    static std::string format(const T& v) { return std::to_string(v); }
};

// Full specialization for bool
template <>
struct Formatter<bool> {
    static std::string format(bool v) { return v ? "yes" : "no"; }
};

// Full specialization for std::string
template <>
struct Formatter<std::string> {
    static std::string format(const std::string& v) { return "\"" + v + "\""; }
};

// Partial specialization for any std::vector<T>
template <typename T>
struct Formatter<std::vector<T>> {
    static std::string format(const std::vector<T>& v) {
        std::string out = "[";
        for (std::size_t i = 0; i < v.size(); ++i) out += (i ? ", " : "") + Formatter<T>::format(v[i]);
        return out + "]";
    }
};

// Partial specialization for any pointer
template <typename T>
struct Formatter<T*> {
    static std::string format(T* p) { return p ? "ptr to " + Formatter<T>::format(*p) : "null"; }
};

template <typename T>
std::string show(const T& v) { return Formatter<T>::format(v); }

// The if constexpr alternative: one template, compile-time branches
template <typename T>
std::string kind_of(const T&) {
    if constexpr (std::is_same_v<T, bool>) return "boolean";
    else if constexpr (std::is_integral_v<T>) return "integer";
    else if constexpr (std::is_floating_point_v<T>) return "decimal";
    else return "other";
}

int main() {
    int n = 7;
    std::cout << show(42) << '\n';
    std::cout << show(true) << '\n';
    std::cout << show(std::string("Rent")) << '\n';
    std::cout << show(std::vector<int>{ 1, 2, 3 }) << '\n';
    std::cout << show(std::vector<bool>{ true, false }) << '\n';
    std::cout << show(std::vector<std::string>{ "Food", "Travel" }) << '\n';
    std::cout << show(&n) << ", " << show(static_cast<int*>(nullptr)) << '\n';
    std::cout << kind_of(true) << ' ' << kind_of(10) << ' ' << kind_of(2.5) << ' ' << kind_of("txt") << '\n';
    return 0;
}

/* Output:
42
yes
"Rent"
[1, 2, 3]
[yes, no]
["Food", "Travel"]
ptr to 7, null
boolean integer decimal other
*/