Re:The joy of max()
by andrepd on Friday March 30, 2018 @08:34PM
(#16720940)
This in cpp:
[ Parent
| on HN ]
Edit: apologies, I'm blind; never mind. I thought I double-checked but the use of > instead of < tripped me up.
Stepanov disagrees. You should return the second parameter if a, b are equivalent (and you should use < anyway):
template<typename T>
inline constexpr const T& max(const T& a, const T& b) {
return (b < a ? a : b);
}What’s the reasoning behind this?
I think to be comparable in c++ types are required to implement < operator and the same is exclusively used by the stdlib.
If you sort2(a, b), it would be nice if min(a, b) == a && max(a, b) == b.
The C version works with distinct types for a and b. Does this?
That's not a feature, it's more bug prone.
This one works too, if they are implicitly convertible (e.g. max(1, 2.0))