Skip to main content

Lesson 3 of 6

Template Specialisation - Full & Partial

**Full specialisation** provides a completely custom implementation for a specific set of type arguments. **Partial specialisation** (only available for class templates, not function templates) provides a custom implementation for a subset of possible type arguments (e.g., 'all pointer types'). Template specialisation is how the standard library implements special behaviour for `bool` (in `std::vector<bool>`) and `void` (in `std::optional<void>`).

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Full & Partial Specialisation - TypeTraits Pattern

Full & Partial Specialisation - TypeTraits Pattern
#include <iostream>
#include <string>
#include <sstream>

// ── Primary template ──────────────────────────────────────────
template<typename T>
struct Serializer {
    static std::string to_string(const T& val) {
        std::ostringstream oss;
        oss << val;   // requires T to have operator<<
        return oss.str();
    }
    static T from_string(const std::string& s) {
        T val;
        std::istringstream(s) >> val;
        return val;
    }
};

// ── Full specialisation for bool ──────────────────────────────
template<>
struct Serializer<bool> {
    static std::string to_string(bool val) {
        return val ? "true" : "false";
    }
    static bool from_string(const std::string& s) {
        return s == "true" || s == "1";
    }
};

// ── Full specialisation for std::string ───────────────────────
template<>
struct Serializer<std::string> {
    static std::string to_string(const std::string& val) {
        return '"' + val + '"';   // JSON-style quoting
    }
    static std::string from_string(const std::string& s) {
        if (s.size() >= 2 && s.front()=='"' && s.back()=='"')
            return s.substr(1, s.size()-2);  // strip quotes
        return s;
    }
};

// ── Partial specialisation - all pointer types ─────────────────
template<typename T>
struct Serializer<T*> {
    static std::string to_string(const T* ptr) {
        if (!ptr) return "null";
        return "ptr:" + Serializer<T>::to_string(*ptr);
    }
};

// ── Type traits via specialisation ────────────────────────────
template<typename T> struct is_pointer        : std::false_type {};
template<typename T> struct is_pointer<T*>   : std::true_type  {};
template<typename T> struct is_pointer<T**>  : std::true_type  {};

template<typename T>
struct remove_pointer       { using type = T; };
template<typename T>
struct remove_pointer<T*>   { using type = T; };  // strips one *

int main() {
    // Uses primary template
    std::cout << Serializer<int>::to_string(42)     << "
";   // 42
    std::cout << Serializer<double>::to_string(3.14)<< "
";   // 3.14

    // Uses bool specialisation
    std::cout << Serializer<bool>::to_string(true)  << "
";   // true
    std::cout << Serializer<bool>::to_string(false) << "
";   // false

    // Uses string specialisation
    std::cout << Serializer<std::string>::to_string("hello") << "
"; // "hello"

    // Uses pointer partial specialisation
    int x = 99;
    std::cout << Serializer<int*>::to_string(&x)  << "
";  // ptr:99
    std::cout << Serializer<int*>::to_string(nullptr) << "
"; // null

    // Type trait
    std::cout << is_pointer<int>::value  << "
";   // 0
    std::cout << is_pointer<int*>::value << "
";   // 1

    using pi_type = remove_pointer<int*>::type;     // int
    static_assert(std::is_same_v<pi_type, int>);

    return 0;
}

Common Mistakes

  • Function templates cannot be partially specialised - partial specialisation only works for class templates. For function templates, use overloading or a class template helper with a static function.
  • Specialisation must be in the same namespace as the primary template - `template<> struct std::hash<MyType>` must be in namespace `std` (allowed by the standard for user-defined types).
  • Specialisations must be declared after the primary template - the primary template must be visible before any of its specialisations, but specialisations must be visible before they are used. Typically: primary in a header, specialisations in the same header or a separate header included after.

Tip

Tip

Practice Template Specialisation Full Partial in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Customizing Template Implementations for Specific Types (e.g. std::vector<bool> bitmask optimization)

Practice Task

Note

Practice Task - (1) Write a working example of Template Specialisation Full Partial from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Template Specialisation Full Partial is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • **Full specialisation** provides a completely custom implementation for a specific set of type arguments.
  • Function templates cannot be partially specialised - partial specialisation only works for class templates. For function templates, use overloading or a class template helper with a static function.
  • Specialisation must be in the same namespace as the primary template - `template<> struct std::hash<MyType>` must be in namespace `std` (allowed by the standard for user-defined types).
  • Specialisations must be declared after the primary template - the primary template must be visible before any of its specialisations, but specialisations must be visible before they are used. Typically: primary in a header, specialisations in the same header or a separate header included after.

Topics in This Module

0/6 done