Small contribution to algorithm library: clamp function

I wasn't able to find a clamp function in boost so i submitted my version for discussion and refinement here: http://www.boostpro.com/vault/index.php?&direction=0&order=&directory=Algorithms (file clamp.hpp) Summary: clamp(a, x, b) Effect: if (x < a) returns a, otherwise if (b < x) returns b, otherwise returns x. clamp(a, x, b, comp) clamp<comp>(a, x, b) Effect: if comp(x, a) returns a, otherwise if comp(b, x) returns b, otherwise returns x. Let me know what you think. Maybe i was wrong and such function does already exist within boost?

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: http://www.boostpro.com/vault/index.php?&direction=0&order=&directory=Algorithms (file clamp.hpp)
Summary: clamp(a, x, b) Effect: if (x < a) returns a, otherwise if (b < x) returns b, otherwise returns x.
clamp(a, x, b, comp) clamp<comp>(a, x, b) Effect: if comp(x, a) returns a, otherwise if comp(b, x) returns b, otherwise returns x.
I have one in my (soon to be proposed) Boost.Algorithm library. Interesting that you were successful at uploading to the vault. I have been stymied by that :-( ] Here's my version - it appears to be basically the same as yours. ;-) -- Marshall Marshall Clow Idio Software <mailto:mclow.lists@gmail.com> A.D. 1517: Martin Luther nails his 95 Theses to the church door and is promptly moderated down to (-1, Flamebait). -- Yu Suzuki

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: http://www.boostpro.com/vault/index.php?&direction=0&order=&directory=Algorithms (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) : forward<U>(upper); } 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 overloads... - Jeff
participants (3)
-
Jeffrey Lee Hellrung, Jr.
-
Marshall Clow
-
Тимофей Игнатьич