C++ Templates - The Complete Guide, 2nd Edition introduces the max template:
template<typename T>
T max (T a, T b)
{
// if b < a then yield a else yield b
return b < a ? a : b;
}
And it explains using “b < a ? a : b”
instead of “a < b ? b : a”
:
Note that the max() template according to [StepanovNotes] intentionally returns “b < a ? a : b” instead of “a < b ? b : a” to ensure that the function behaves correctly even if the two values are equivalent but not equal.
How to understand "even if the two values are equivalent but not equal.
"? “a < b ? b : a”
seems have the same result for me.
a
andb
are equivalent, then!(a < b) && !(b < a)
is true, soa < b
andb < a
are both false, so inb < a ? a : b
,b
is returned, which is not what you want... You wanta < b ? b : a
.a = max(a, b);
(repeatedly) you might not want to replacea
unnecessarily.a
with a copy ofa
).std::addressof
is irrelevant. In fact, for the givenT max(T a, T b)
we already knowaddressof(a) != addressof(b)
.