
Andrew wrote:
... Since it's semantically valid to have an un-initialized optional type, I think failure to extract something off a stream should return an empty optional type _without_ setting the failbit on the stream.
Andrew, sorry for the late reply. optional<T> is about initialized versus uninitialized value, it has nothing to do with stream's state. IMO, the failbit should be set. My vision of optional<T> streaming is based on this quote from documentation: "optional<T> intends to formalize the notion of initialization (or lack of it) allowing a program to test whether an object has been initialized and stating that access to the value of an uninitialized object is undefined behavior." Thus, - after a successful read the stream is in a good state and the value is initialized, - after read failure, the failbit bit is set and the value is uninitialized, - printing of initialized optional<T> value produces the same result as printing T value, - printing of uninitialized value sets the failbit.
However there is still one problem, and this brings us back to lexical_cast. Consider this example: int an_invalid_uint = -1; unsigned i = lexical_cast<optional<unsigned> > (an_invalid_uint).get_value_or (0); ... So is there any interest in this sort of refinement of optional's InputStreamable implementation or lexical_cast?
My streaming proposal makes lexical_cast < optional<T> >(v) equivalent to lexical_cast<T>(v) because it would never return uninitialized value. I can use it as a good excuse for implementing no-throw version of lexical_cast < optional<T> >(v) ;-) Alex