gpt4 book ai didi

c++ - 为什么使用 “b < a ? a : b” 而不是 “a < b ? b : a” 来实现最大模板?

转载 作者:IT老高 更新时间:2023-10-28 11:30:47 27 4
gpt4 key购买 nike

C++ Templates - The Complete Guide, 2nd Edition介绍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 ? a : b”而不是 “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.

如何理解“even if the two values are equivalent but not equal.”? “a < b ? b : a”对我来说似乎有相同的结果。

最佳答案

std::max(a, b) 确实被指定为在两者相等时返回 a

Stepanov 认为这是一个错误和其他因为它破坏了给出 ab 的有用属性,你总是可以用 {min(a, b), max(a, b )};为此,您希望 max(a, b) 在参数相等时返回 b

关于c++ - 为什么使用 “b < a ? a : b” 而不是 “a < b ? b : a” 来实现最大模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50834117/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com