http://en.cppreference.com/w/cpp/algorithm/clamp gives this as a possible implementation for std::clamp
:
template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ) { return assert( !comp(hi, lo) ), comp(v, lo) ? lo : comp(hi, v) ? hi : v; }
While I do understand how this works, putting the assert statement in the return seems rather strange to me; I would have written it as:
template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ) { assert( !comp(hi, lo) ); return comp(v, lo) ? lo : comp(hi, v) ? hi : v; }
Still, I'm guessing they chose their implementation for a reason; is there advantage of their version over "mine"?
Syntax. The comma operator separates expressions (which have value) in a way analogous to how the semicolon terminates statements, and sequences of expressions are enclosed in parentheses analogously to how sequences of statements are enclosed in braces: (a, b, c) is a sequence of expressions, separated by commas,...
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop. The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.
The comma can be used in return statements, to assign to a global variable or out parameter (passed by reference). This idiom suggests that the assignments are part of the return, rather than auxiliary assignments in a block that terminates with the actual return. For example, in setting a global error number:
In C++, we can overload the comma operator using Operator Overloading. For Example: For “ Send the query X to the server Y and put the result in variable Z”, the “and” plays the role of the comma. The comma operator (, ) is used to isolate two or more expressions that are included where only one expression is expected.
In C++11, constexpr
functions could only have a single return statement (see here). The suggested implementation allows the function to be used in a C++11 compliant compiler.
C++14 removed this restriction, so your implementation is also valid in C++14 or later.
Disregarding this, the functions are exactly equivalent, and your one is definitely more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With