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

前端 未结 6 1803
忘了有多久
忘了有多久 2021-02-01 11:24

This is the code from the C++ standard library remove code. Why is inequality tested as if (!(*first == val)) instead of if (*first != val)

6条回答
  •  面向向阳花
    2021-02-01 12:07

    This is the code from the C++ standard library remove code.

    Wrong. It's not the C++ standard library remove code. It's one possible internal implementation of the C++ standard library remove function. The C++ standard does not prescribe actual code; it prescibes function prototypes and required behaviours.

    In other words: From a strict language point of view, the code you are seeing does not exist. It may be from some header file that comes with your compiler's standard-library implementation. Note that the C++ standard does not even require those header files to exist. Files are just a convenient way for compiler implementors to meet the requirements for a line like #include (i.e. making std::remove and other functions available).

    Why is inequality tested as if (!(*first == val)) instead of if (*first != val) ?

    Because only operator== is required by the function.

    When it comes to operator overloading for custom types, the language allows you to do all kinds of weird things. You could very well create a class which has an overloaded operator== but no overloaded operator!=. Or even worse: You could overload operator!= but have it do completely unrelated things.

    Consider this example:

    #include 
    #include 
    
    struct Example
    {
        int i;
    
        Example() : i(0) {}
    
        bool operator==(Example const& other) const
        {
            return i == other.i;
        }
    
        bool operator!=(Example const& other) const
        {
            return i == 5; // weird, but nothing stops you
                           // from doing so
        }
    
    };
    
    int main()
    {
      std::vector v(10);
      // ...
      auto it = std::remove(v.begin(), v.end(), Example());
      // ...
    }
    

    If std::remove used operator!=, then the result would be quite different.

提交回复
热议问题