Templates and Generics
Templates and Generics
Function templates, class templates, constraints, and generic programming patterns.
Templates and Generics
Function templates, class templates, constraints, and generic programming patterns.
template <typename T>
T max_of(T a, T b) {
return a > b ? a : b;
}
template <typename T>
class Box {
public:
explicit Box(T value) : value_{std::move(value)} {}
const T& get() const { return value_; }
private:
T value_;
};
template <typename T, std::size_t N>
class FixedBuffer {
std::array<T, N> data_{};
};
requirestemplate <typename T>
concept Addable = requires(T a, T b) {
a + b;
};
template <Addable T>
T sum(T a, T b) {
return a + b;
}
std::is_same_v<T, U>std::is_integral_v<T>std::enable_if_t<...>std::remove_reference_t<T>std::integral auto clamp_positive(std::integral auto value) {
return value < 0 ? 0 : value;
}
Abbreviated templates are convenient for small interfaces, but named template parameters are usually clearer for bigger APIs.
requires clauses and nested requirementstemplate <typename T>
concept Reservable = requires(T container, std::size_t n) {
container.reserve(n);
typename T::value_type;
};
template <typename T>
requires Reservable<T>
void prepare(T& container, std::size_t n) {
container.reserve(n);
}
std::remove_cvref_t<T>std::type_identity_t<T>std::is_invocable_v<F, Args...>std::conditional_t<cond, A, B>if constexpr helpsUse if constexpr to keep one generic algorithm readable instead of splitting simple type-based branches into separate overloads.