C++C++ Explainer
C++ · 4 · Templates & Generic Programming17 / 36 · 47%

Class Templates & Specialization

Generic by default, hand-tuned for the types that need it.

Examples: template<class T> class, full & partial specialization

shortcuts: ← prev · → next · M mark
1

Class Template

One definition, any element type.

Example
example
template <typename T>
class Stack {
    std::vector<T> data_;
public:
    void push(const T& v) { data_.push_back(v); }
    T    pop() { T v = data_.back(); data_.pop_back(); return v; }
    bool empty() const { return data_.empty(); }
};

Stack<int> si; Stack<std::string> ss;
2

Full Specialization

Replace the whole implementation for one exact type.

Example
example
template <typename T> struct Serializer {
    static std::string to_text(const T& v) { return std::to_string(v); }
};

template <> struct Serializer<bool> {
    static std::string to_text(bool v) { return v ? "true" : "false"; }
};
3

Partial Specialization

Match a family of types, e.g. any pointer.

Example
example
template <typename T> struct Traits            { static constexpr bool is_ptr = false; };
template <typename T> struct Traits<T*>        { static constexpr bool is_ptr = true;  };
template <typename K, typename V> struct Traits<std::pair<K,V>> { /* ... */ };
TIP
Function templates cannot be partially specialized — overload them instead.
4

Where Templates Live

Templates are instantiated at use, so definitions belong in headers.

Common pitfalls
  • ✕Defining a template in a .cpp gives "undefined reference" at link time.
  • ✕Heavy template use bloats compile times and binary size.
  • ✕Template error messages are long — read the FIRST error, not the last.