为什么使用“ b<一种 ? a:b”而不是“ a< ? b:一个”以实现最大模板? [英] Why use “b < a ? a : b” instead of “a < b ? b : a” to implement max template?
问题描述
C ++模板-完整指南,第二版介绍了 max 模板:
template<typename T>
T max (T a, T b)
{
// if b < a then yield a else yield b
return b < a ? a : b;
}
并使用 b<一种 ? a:b
而不是 a< ? b:a
:
请注意,根据[StepanovNotes]
的max()模板故意返回 b<一种 ? a:b而不是 a< ? 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.
如何理解 ,即使两个值相等但不相等。
? a< ? b:a
似乎对我有相同的结果。
How to understand "even if the two values are equivalent but not equal.
"? "a < b ? b : a"
seems have the same result for me.
推荐答案
实际上,将std :: max(a,b)
指定为在两者相等时返回 a
。
std::max(a, b)
is indeed specified to return a
when the two are equivalent.
That's considered a mistake by Stepanov and others because it breaks the useful property that given a
and b
, you can always sort them with {min(a, b), max(a, b)}
; for that, you'd want max(a, b)
to return b
when the arguments are equivalent.
这篇关于为什么使用“ b<一种 ? a:b”而不是“ a< ? b:一个”以实现最大模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!