CKTIS / C++
std::clamp: constraining a value to an interval
std::clamp returns the lower bound, upper bound, or value itself so the result lies in an ordered interval.
Version: C++23
Syntax
template<class T>
constexpr const T& clamp(const T& value, const T& low, const T& high);
template<class T, class Compare>
constexpr const T& clamp(const T& value, const T& low, const T& high, Compare comp);std::clamp(v, lo, hi, comp) from <algorithm> first tests comp(v, lo) and returns a reference to lo, then tests comp(hi, v) and returns a reference to hi, otherwise returning a reference to v. In C++23, the overload without a comparator uses std::less{}. At most two comparisons are performed.
A precondition is that hi does not precede lo under the comparator. Violating this precondition causes undefined behavior; the function does not swap the bounds automatically. The comparator must provide a consistent ordering; for floating-point inputs, NaN values break the usual ordering assumptions.
The result type is const T&. Copying it immediately is safe, but retaining the reference can dangle when v, lo, or hi was a temporary. When v is equivalent to both bounds, both comparisons are false and the result refers to v. The function does not modify its arguments.
Examples
#include <algorithm>
#include <iostream>
int main() {
const int bounded = std::clamp(12, 0, 10);
std::cout << bounded << '\n';
}
Result
10
std::clamp → 10