std::clamp (3) - Linux Manuals
std::clamp: std::clamp
NAME
Synopsis
Defined in header <algorithm>
template<class T> (1) (since C++17)
constexpr const T& clamp( const T& v, const T& lo, const T& hi );
template<class T, class Compare> (2) (since C++17)
constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp );
1) If v compares less than lo, returns lo; otherwise if hi compares less than v, returns hi; otherwise returns v. Uses operator< to compare the values.
2) Same as (1), but uses comp to compare the values.
The behavior is undefined if the value of lo is greater than hi
Parameters
v - the value to clamp
lo,hi - the boundaries to clamp v to
comp - While the signature does not need to have const &, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value_category (thus, Type1 & is not allowed
Type requirements
-
T must meet the requirements of LessThanComparable in order to use overloads (1).
Return value
Reference to lo if v is less than lo, reference to hi if hi is less than v, otherwise reference to v.
Complexity
At most two comparisons.
Possible implementation
First version
Second version
Notes
Capturing the result of std::clamp by reference if one of the parameters is rvalue produces a dangling reference if that parameter is returned:
If v compares equivalent to either bound, returns a reference to v, not the bound.
Only works for floating-point T if NaNs are avoided.
Example
// Run this code
Possible output:
See also
min (function template)
max (function template)