Search code examples
c++language-lawyerc++20spaceship-operator

Implied meaning of ordering types in C++20


C++20 allows users to specify different return types when defining operator <=>: std::partial_ordering, std::weak_ordering and std::strong_ordering. Does specifying them imply that corresponding class promises to obey certain ordering axioms? E.g. for partial ordering those would be irreflexivity, asymmetry and transitivity.

I couldn't find any mentions of this in C++20 standard.


Solution

  • Yes, that's definitely the intent of categories.

    All the orderings should be irreflexive, asymetric, and transitive. weak_ordering and strong_ordering should be total orders. strong_ordering implies substitutability (i.e. that a == b implies f(a) == f(b), for a collection of functions f for which this question makes sense -- for instance std::addressof is not one such function).

    This isn't in the C++ standard because it's not really a matter of the rules of the language - it's a matter of what you should or should not do as a programmer. Like if you declare operator<=> that returns strong_ordering, it should absolutely be a valid ordering that satisfies substitutability - but that's, at best, maybe a note, and would feel out of place in the rest of the document.

    But you can read more of the original ordering papers to get a sense of intent, like P0100 and P0515.