It is very useful to be able to compare for equality a std::optional<T>
with T
:
std::optional<int> opt_value;
int value = 123;
opt_value == value; // will always be 'false'
I think the behavior in this case is well defined and clear.
What I do not get is why is this allowed:
opt_value < value; // this will always be 'true'
I was expecting this to not even compile. I think it is very obscure what is happening here. What is the reason why this has been even added to the STL?
std::optional
, and sort it. Or otherwise usestd::optional
when ordering is expected. – Averir==
but question the utility of<
? – Declamationnullopt
always less then any other value is completely arbitrary. Since many of these not obvious default behavior normally do not get into the standard, I was wondering why this specific one could instead get in. – Scribbleropt_value == value
(for value types that supportoperator==
any more semantically meaningful thanopt_value < value
(for value types that supportoperator<
) with the possible exception that it feels more "obvious" thatnullopt_t != value
whereas it's not that intuitive what the ordering of a null optional and an actual value should be. But "empty optionals are less than all values" isn't that weird imo. – Barometrographnullopt
always less then any other value is completely arbitrary." So what? Just because it's arbitrary doesn't make it wrong. – Canonessoperator==
andoperator!=
. Is a very implicit obscure behavior. Many proposal normally do not even get into the standard for more trivial reasons than this one. – Scribbleroptional<T>
is to be comparable: less than allT
s, or greater than allT
s. – Canonessoptional<T>
is comparable withT
which is what is being discussed. There is a third scenario, one whereoptional<T>
could be non-comparable withT
. Edit : this is resolved in your answer. – Mathian