Boost logo

Boost :

Subject: Re: [boost] Small contribution to algorithm library: clamp function
From: Jeffrey Lee Hellrung, Jr. (jhellrung_at_[hidden])
Date: 2011-02-23 12:37:50

On 2/23/2011 6:35 AM, Marshall Clow wrote:
> On Feb 22, 2011, at 11:54 PM, Тимофей Игнатьич wrote:
>> I wasn't able to find a clamp function in boost so i submitted my version for discussion and refinement here:
>> (file clamp.hpp)
> Here's my version - it appears to be basically the same as yours. ;-)

You may consider passing by reference, making all 3 parameters types
independent, and using common_type (which I believe has been recently
added to Boost.TypeTraits...?):

template< class L, class T, class U >
typename common_type<T,L,U>::type
clamp(L&& lower, T&& x, U&& upper)
     return !(upper < x) ? !(x < lower) ?
            forward<T>(x) :
            forward<L>(lower) :

Also, this prefers returning x over either lower or upper when x
compares equivalently to lower or upper.

For a strictly C++03 implementation...I guess you can emulate the rvalue
references by providing all 8 variations of reference to const/non-const

- Jeff

Boost list run by bdawes at, gregod at, cpdaniel at, john at