C++ · Module 12 · Lesson 21 min read

Class Templates

Declaring a class template

arduino
template <typename T>
class Box {
public:
    explicit Box(T value) : value_(std::move(value)) {}
    const T& get() const { return value_; }
private:
    T value_;
};

Box<int> a(5);
Box<std::string> b("hello");

Member functions outside the class

arduino
template <typename T>
const T& Box<T>::get() const { return value_; }

(Usually defined inside the class for templates.)

Class Template Argument Deduction (CTAD, C++17)

c
Box c(3.14);                  // Box<double> deduced
std::vector v = { 1, 2, 3 };  // std::vector<int>
std::pair p(1, "one");        // std::pair<int, const char*>

Multiple parameters & defaults

perl
template <typename K, typename V = int>
class Pair { ... };
Pair<std::string> p;          // V defaults to int

Non-type parameters

arduino
template <typename T, std::size_t Capacity>
class FixedStack { std::array<T, Capacity> data_; ... };
FixedStack<int, 10> s;        // capacity fixed at compile time (like std::array)

Each instantiation is a different type

Box<int> and Box<double> are unrelated types — you can't assign one to the other unless you write a converting constructor.

Static members

Each instantiation gets its own copy of static members.

Writing a generic container

A typical generic container needs: storage, push/pop/size/empty, element access with bounds checking, and ideally begin()/end() so it works with range-for and algorithms (Unit 19 project).

Type aliases

arduino
template <typename T>
using Matrix = std::vector<std::vector<T>>;
Matrix<double> m;

Example

C++
#include <array>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>

template <typename T, std::size_t Capacity>
class FixedStack {
public:
    void push(const T& value) {
        if (size_ == Capacity) throw std::overflow_error("stack full");
        data_[size_++] = value;
    }
    T pop() {
        if (size_ == 0) throw std::underflow_error("stack empty");
        return data_[--size_];
    }
    const T& top() const { return data_.at(size_ - 1); }
    std::size_t size() const { return size_; }
    bool empty() const { return size_ == 0; }
    static constexpr std::size_t capacity() { return Capacity; }
private:
    std::array<T, Capacity> data_{};
    std::size_t size_ = 0;
};

template <typename K, typename V = int>
struct Entry {
    K key;
    V value;
    void print() const { std::cout << key << " -> " << value << '\n'; }
};

template <typename T>
class Counter {
public:
    Counter() { ++instances_; }
    static int instances() { return instances_; }
private:
    static inline int instances_ = 0;              // one counter per instantiation
};

template <typename T>
class Box {
public:
    explicit Box(T v) : value_(std::move(v)) {}
    const T& get() const { return value_; }
private:
    T value_;
};

int main() {
    FixedStack<std::string, 3> undo;
    undo.push("add expense");
    undo.push("edit budget");
    undo.push("delete note");
    std::cout << "capacity " << undo.capacity() << ", top: " << undo.top() << '\n';
    try {
        undo.push("one more");
    } catch (const std::overflow_error& e) {
        std::cout << "error: " << e.what() << '\n';
    }
    while (!undo.empty()) std::cout << "undo " << undo.pop() << '\n';

    Entry<std::string> e1{ "visits", 42 };                 // V defaults to int
    Entry<std::string, double> e2{ "rating", 4.7 };
    e1.print();
    e2.print();

    Counter<int> a, b;
    Counter<double> c;
    std::cout << "Counter<int>: " << Counter<int>::instances()
              << ", Counter<double>: " << Counter<double>::instances() << '\n';

    Box price(499.99);                                      // CTAD: Box<double>
    Box label(std::string("Rent"));                         // Box<std::string>
    std::cout << label.get() << ": " << price.get() << '\n';
    (void)a; (void)b; (void)c;
    return 0;
}

/* Output:
capacity 3, top: delete note
error: stack full
undo delete note
undo edit budget
undo add expense
visits -> 42
rating -> 4.7
Counter<int>: 2, Counter<double>: 1
Rent: 499.99
*/