**Document number**: N4536**Date**: 2015-05-17**Project**: Programming Language C++, Library Evolution Working Group

**Reply to**: Martin Moene <martin.moene (at) gmail.com>, Niels Dekker <n.dekker (at) xs4all.nl>

Introduction

Motivation

Impact on the standard

Comparison to clamp of Boost.Algorithm

Design decisions

Proposed wording

Possible implementation

Acknowledgements

References

The algorithm proposed here "clamps" a value between a pair of boundary values. The idea and interfaces are inspired by clamp in the Boost.Algorithm library authored by Marshall Clow.

It is a common programming task to constrain a value to fall within certain limits. This can be expressed in numerous ways, but it would be good if such an operation can be easily recognized and doesn't appear in many guises just because it can.

So, we'd like to have a concise way to obtain a value that is forced to fall within a range we request, much like we can limit a value to a defined minimum or maximum. For example:

`auto clamped_value = clamp( value, min_value, max_value );`

Without a standardized way, people may (need to) define their own version of "clamp" or resort to a less clear solution such as^{1}:

`auto clamped_value = std::min( std::max( value, min_value ), max_value );`

For convenience we also propose an algorithm to clamp a series of values:

```
std::vector<int> v{ 1,2,3,4,5,6,7,8,9 };
auto clamped_v = clamp_range( v.begin(), v.end(), v.begin(), 3, 7 );
```

In addition to the boundary values, one can provide a predicate that evaluates if a value is within the boundary.

```
struct rgb{ ... };
auto clamped_rgb = clamp( rgb_value, rgb_lo, rgb_hi, rgb_compare );
```

Function `clamp()`

already exists in C++ libraries such as Boost [1] and Microsoft AMP [2]. The Qt Project provides `qBound`

[3] , and the Python library scipy/numpy provides `clip()`

[4] for the same purpose.

The clamp algorithms can be implemented as a pure library extension in C++14. The proposed wording is dependent on the void specialization of `<functional>`

's operator functors that is available since C++14 [5][6].

Our proposal defines a single function that can be used both with a user-defined predicate and without it. When no predicate is specified, the comparator defaults to `std::less<void>()`

. The void specialization of `<functional>`

's operator functors introduced in C++14 enables comparison using the proper type [5][6].

Boost's clamp on the other hand was conceived before C++14 and uses two separate functions. Also, supporting compatibility with different versions of C++ is a reason for a Boost library to not require C++14-specific properties.

Like `std::min()`

and `std::max()`

, `clamp()`

requires its arguments to be of the same type, whereas, Boost's clamp accepts arguments of different type.

We chose the name *clamp* as it is expressive and is already being used in other libraries ^{2}. Another name could be *limit*. Other names for *clamp_range* could be *clamp_elements*, or *clamp_transform*.

`clamp()`

can be regarded as a sibling of `std::min()`

and `std::max()`

. This makes it desirable to follow their interface using constexpr, passing parameters by const reference and returning the result by const reference. Passing values by `const &`

is desired for types that have a possibly expensive copy constructor such as `cpp_int`

of Boost.Multiprecision [7] and `std::seminumeric::integer`

from the Proposal for Unbounded-Precision Integer Types [8].

With the void specialization of `<functional>`

's operator functors available in C++14, we chose to combine the predicate and non-predicate versions into a single function and make `std::less<>()`

its default comparator.

```
template<class T, class Compare = std::less<>>
constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp = Compare() );
```

1 *Requires*: Type `T`

is `LessThanComparable`

(Table 18).

2 *Returns*: The larger value of `v`

and `lo`

if `v`

is smaller than `hi`

, otherwise the smaller value of `v`

and `hi`

.

3 *Complexity*: `clamp`

will call `comp`

either one or two times before returning one of the three parameters.

4 *Remarks*: Returns the first argument when it is equivalent to one of the boundary arguments.

```
template<class InputIterator, class OutputIterator, class Compare = std::less<>>
OutputIterator clamp_range( InputIterator first, InputIterator last, OutputIterator result,
typename std::iterator_traits<InputIterator>::value_type const& lo,
typename std::iterator_traits<InputIterator>::value_type const& hi, Compare comp = Compare() );
```

1 *Requires*: T is `LessThanComparable`

(Table 18) and `CopyAssignable`

(Table 23).

2 *Returns*: `result + (last - first)`

.

3 *Complexity*: Exactly `last - first`

applications of `clamp`

with the corresponding predicate.

4 *Remarks*: `result`

may be equal to `first`

.

A reference implementation of this proposal can be found at GitHub [9].

Clamp a value per predicate:

```
template<class T, class Compare>
constexpr const T& clamp( const T& val, const T& lo, const T& hi, Compare comp )
{
return assert( !comp(hi, lo) ),
comp(val, lo) ? lo : comp(hi, val) ? hi : val;
}
```

Clamp range of values per predicate:

```
template<class InputIterator, class OutputIterator, class Compare>
OutputIterator clamp_range(
InputIterator first, InputIterator last, OutputIterator result,
typename std::iterator_traits<InputIterator>::value_type const& lo,
typename std::iterator_traits<InputIterator>::value_type const& hi, Compare comp )
{
using arg_type = decltype(lo);
return std::transform(
first, last, result, [&](arg_type val) -> arg_type { return clamp(val, lo, hi, comp); } );
}
```

Thanks to Marshall Clow for Boost.Algorithm's clamp which inspired this proposal and to Jonathan Wakely for his help with the proposing process.

[1] Marshall Clow. clamp in the Boost Algorithm Library.

Note: the Boost documentation shows `clamp()`

using pass by value, whereas the actual code in boost/algorithm/clamp.hpp uses `const &`

. See ticket 10081.

[2] Microsoft. C++ Accelerated Massive Parallelism library (AMP).

[3] Qt Project. Documentation on qBound.

[4] Scipy.org. Documentation on numpy.clip.

[5] Stephan T. Lavavej. Making Operator Functors greater<> (N3421, HTML). 2012-09-20.

[6] ISO/IEC. Working Draft, Standard for Programming Language C++ (N4296, PDF). Section 20.9.6. 2014-11-19.

[7] John Maddock. Boost.Multiprecision.

[8] Pete Becker. Proposal for Unbounded-Precision Integer Types (N4038).

[9] Martin Moene. Clamp algorithm (GitHub).