Templates and Generic Code
Templates and Generic Code
Write reusable functions and classes that work across multiple types.
Templates and Generic Code
Write reusable functions and classes that work across multiple types.
template <typename T>
T add(T a, T b) {
return a + b;
}
One implementation can support many types without runtime overhead.
template <typename T>
class Holder {
public:
explicit Holder(T value) : value_{std::move(value)} {}
const T& get() const { return value_; }
private:
T value_;
};
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.
std::is_integral_v<T>std::is_same_v<T, U>std::remove_cvref_t<T>std::is_invocable_v<F, Args...>Start with the simplest generic function that works, then add constraints only when the interface becomes unclear or misuse is likely.