Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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"?

like image 806
Kullackov Avatar asked Aug 01 '19 08:08

Kullackov


1 Answers

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.

like image 95
rubenvb Avatar answered Oct 29 '22 18:10

rubenvb