This is the code from the C++ standard library remove
code. Why is inequality tested as if (!(*first == val))
instead of if (*first != val)
The most promising approach is to find a method of determining if operator== can be called for a particular type, and then supporting it only when it is available; in other situations, an exception would be thrown. However, to date there is no known way to detect if an arbitrary operator expression f == g is suitably defined. The best solution known has the following undesirable qualities:
- Fails at compile-time for objects where operator== is not accessible (e.g., because it is private).
- Fails at compile-time if calling operator== is ambiguous.
- Appears to be correct if the operator== declaration is correct, even though operator== may not compile.
From Boost FAQ : source
Knowing that requiring ==
implementation is a burden, you never want to create additional burden by requiring !=
implementation as well.
For me personally it's about SOLID (object-oriented design) L part - Liskov substitution principle : “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”. In this case it is the operator != that i can replace with == and boolean inverse in boolean logic.