Is there a reasonably idiomatic way* to use stream insertion operators >> with std::optional? The standard class does not provide an overload for std::istream& operator>>(std::istream& is, std::optional<T>& obj), and I believe using
std::optional<int> i{};
stream >> *i;
invokes undefined behavior if i does not already have a value.
*Yes I am aware that nothing about streams is idiomatic or natural...
You're right.
*iis undefined behavior for an emptystd::optional. What you should do instead is:Instead of an immediately-invoked lambda expression (IILE), you could also write a utility function that does this for you: