Why is inequality tested as (!(a==b)) in a lot of C++ standard library code?

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;
 }

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==.


Most functions in STL work only with operator< or operator==. This requires the user only to implement these two operators (or sometimes at least one of them). For example std::set uses operator< (more precisely std::less which invokes operator< by default) and not operator> to manage ordering. The remove template in your example is a similar case - it uses only operator== and not operator!= so the operator!= doesn't need to be defined.