Templates and Generic Code

Templates and Generic Code

Write reusable functions and classes that work across multiple types.

Templates and Generic Code

A generic function

template <typename T>
T add(T a, T b) {
    return a + b;
}

Why templates are useful

One implementation can support many types without runtime overhead.

A generic class

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

private:
    T value_;
};

Modern advice

Concepts make templates friendlier

template <typename T>
concept Summable = requires(T a, T b) {
    a + b;
};

template <Summable T>
T add_all(T a, T b) {
    return a + b;
}

Good constraints move errors toward the call site and describe the intent of the API.

Useful type traits

Design guidance

Start with the simplest generic function that works, then add constraints only when the interface becomes unclear or misuse is likely.