Search code examples
c++standardsdeprecatedstdc++20

Why will std::rel_ops::operators be deprecated in C++20?


According to cppreference.com, std::rel_ops::operator!=,>,<=,>= will be deprecated in C++20.

What's the rationale behind?


Solution

  • In C++20, you get three-way comparison (operator <=>), which automatically "generates" default comparisons if provided:

    struct A {
       // You only need to implement a single operator.
       std::strong_ordering operator<=>(const A&) const;
    };
    
    // Compiler generates 4 relational operators (you need to default the
    // three-way comparison operator to get == and !=).
    A to1, to2;
    if (to1 > to2) { /* ... */ } // ok
    if (to1 <= to2) { /* ... */ } // ok, single call to <=>
    

    There are multiple advantages of the three-way comparison over std::rel_ops, which is probably why std::rel_ops operators are deprecated. On top of my head:

    • It is more versatile, since, depending on the return type of operator<=> (std::strong_ordering, std::weak_ordering, ...), only relevant operators are generated. See the <compare> header for more information.

    • You do not bring a bunch of templated operator overloads by doing using namespace std::rel_ops.

    • You can ask the compiler to generate the three-way operator for you by defaulting it (auto operator<=>(A const&) = default) — This will basically generate a lexicographic comparison of base classes and non-static data members, plus it will deduce the right type of ordering if the return type is auto.