为什么使用“ b<一种 ? a:b”而不是“ a< ? b:一个”以实现最大模板? [英] Why use “b < a ? a : b” instead of “a < b ? b : a” to implement max template?

查看:113
本文介绍了为什么使用“ b<一种 ? a:b”而不是“ a< ? b:一个”以实现最大模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

Stepanov 认为这是一个错误。 a>和其他选项,因为它破坏了给定 a b 的有用属性,因此您始终可以使用 {min(a,b),max(a,b)} ;为此,您希望 max(a,b)在参数相等时返回 b

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&lt;一种 ? a:b”而不是“ a&lt; ? b:一个”以实现最大模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆