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?
Short answer:
map<optional<int>, int>
You want to be able to use
optional<T>
as amap
key whenT
is usable as a key. Defining the empty state to be either less than or greater than the normal values makes it well behaved.Meanwhile, comparing a plain
T
against anoptional<T>
should just, logically, upgrade the bareT
to anoptional<T>
holding that value. So, providing an overloaded form that takes a bareT
is just an optimization, and should have the same result.