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

前端 未结 3 460
心在旅途
心在旅途 2021-01-07 18:19

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

What\'s the rationale behind?

3条回答
  •  伪装坚强ぢ
    2021-01-07 18:29

    What's the rationale behind?

    rel_ops was deprecated by Library Support for the Spaceship (Comparison) Operator. The paper doesn't list any motivation, but it does appear in the spaceship paper:

    This subsumes namespace std::rel_ops, so we propose also removing (or deprecating) std::rel_ops.

    There are four reasons mentioned in the paper (including correctness and performance). But one big one not mentioned in either paper is that std::rel_ops just... doesn't work. Rule of thumb is that operators are found using ADL. rel_ops doesn't give you ADL-findable operators, it just declares unconstrained function templates like:

    namespace std {
        namespace rel_ops {
            template< class T >
            bool operator!=( const T& lhs, const T& rhs ) 
            {
                return !(lhs == rhs);
            }
        }    
    }
    

    So using algorithms like:

    struct X { ... };
    bool operator<(X const&, X const&) { ... };
    std::sort(values.begin(), values.end(), std::greater<>{});
    

    Just doesn't work, unless you make sure to:

    #include 
    using namespace std::rel_ops;
    

    Fairly consistently everywhere as your first include to ensure that these operators are visible at the point of definition of every function template you could possibly call.

    So operator<=> is just strictly superior:

    • It actually works.
    • You only have to write one function (<=>) instead of two (== and <)
    • Typically, you actually have to write zero functions (= default)
    • Did I mention it actually works?

提交回复
热议问题