Search code examples
c++operator-overloadingcomparisonc++20comparison-operators

!= auto generated from == in C++20?


Is this standard behavior in C++20? I couldn't find anything about it in cppreference.

I've just tried both on Clang and on Visual Studio and it works and it doesn't give me any sort of error or warning. I also checked with the debugger to see if operator== was being called and it was! Does C++20 now allows for the automatic generation of operator!= when operator== is present? Does it default to a sane !(a == b)? If that's so, then that's awesome for C++!


Solution

  • != auto generated from == in C++20?

    Is this standard behavior in C++20?

    Yes. operator!= is auto generated from operator== in C++20.

    Furthermore, all four relational operators are generated if you define operator<=>, and all of the comparison operators are generated if you define operator<=> as defaulted.

    What you want to do in most cases:

    struct example
    {
        std::string a;
        int         b;
    
        auto operator<=>(const example&) const = default;
    };