为什么在许多C ++标准库代码中将不等式测试为(!(a == b))? [英] Why is inequality tested as (!(a==b)) in a lot of C++ standard library code?
本文介绍了为什么在许多C ++标准库代码中将不等式测试为(!(a == b))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是C ++标准库 remove
代码中的代码.为什么不等式被测试为 if(!(* first == val))
而不是 if(* first!= val)
?
This is the code from the C++ standard library remove
code. Why is inequality tested as if (!(*first == val))
instead of if (*first != val)
?
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator result = first;
while (first!=last) {
if (!(*first == val)) {
*result = *first;
++result;
}
++first;
}
return result;
}
推荐答案
因为这意味着对T的唯一要求是实现 operator ==
.您可能要求T具有 operator!=
,但是这里的总体思路是,您应该给模板的用户带来尽可能少的负担,而其他模板确实需要 operator ==
.
Because this means the only requirement on T is to implement an operator==
. You could require T to have an operator!=
but the general idea here is that you should put as little burden on the user of the template as possible and other templates do need operator==
.
这篇关于为什么在许多C ++标准库代码中将不等式测试为(!(a == b))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文