简体   繁体   中英

Why is null std::optional considered less than any value, not more

Is there any math sense in having null std::optional being less than any keeping value? Or is it made only for consistency and there would have been no any difference if it was "more" instead of "less"?

Directly from the proposal (emphasis mine):

A number of ways of including the disengaged state in comparisons have been suggested. The ones proposed, have been crafted such that the axioms of equivalence and strict weak ordering are preserved : disengaged optional<T> is simply treated as an additional and unique value of T equal only to itself; this value is always compared as less than any value of T .

Further on it says

Value nullopt could have been as well considered greater than any value of T . The choice is to a great degree arbitrary. We choose to stick to what boost::optional does.


Taking a look at boost::optional 's take on this, we get from its documentation :

In a similar manner, type optional<T> is LessThanComparable whenever T is LessThanComparable . The optional object containing no value is compared less than any value of T . To illustrate this, if the default ordering of size_t is {0, 1, 2, ...} , the default ordering of optional<size_t> is {boost::none, 0, 1, 2, ...} . This order does not have a practical interpretation. The goal is to have any semantically correct default ordering in order for optional<T> to be usable in ordered associative containers (wherever T is usable).

So no, there is no "maths sense" to this all except for "nothing is less than something". It's an arbitrary choice of no practical consequence only to ensure the type can be used in ordered containers without much hassle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM