C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Add operator>> overloads to std::optional for streaming input

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Sun, 25 Jun 2023 02:31:48 +0300
On 6/25/23 01:37, Kevin Schmidt via Std-Proposals wrote:
> Hello everybody, I would like to propose the following for the new standard:
>
> Motivation:
>
> Currently, std::optional does not have an operator>> defined, so values
> cannot be streamed directly into an std::optional. Users have to
> explicitly extract the value from the stream and assign it to the
> std::optional using emplace() or operator=(). By adding operator>>
> overloads, std::optional can support more intuitive streaming input.
>
> Initial Design Proposition:
>
> template <typename T>
> std::istream& operator>>(std::istream& is, std::optional<T>& opt) {
> T value;
> if (is >> value) {
> opt.emplace(value);
> } else {
> opt.reset();
> }
> return is;
> }
>
> This defines an operator>> that extracts a value of type T from the
> input stream "is" and assigns it to the std::optional<T> object "opt".
> If the extraction succeeds, the value is emplace()d into "opt". If it
> fails, "opt" is reset to an empty state.

This means you cannot read an empty optional from the stream.

Also, if you introduce an operator>>, it is only natural to introduce an
operator<< as well. However you define it, if operator>> is defined as
you propose, a perfect roundtrip is not possible:

void test(std::optional<int> o1)
{
    std::stringstream strm;
    strm << o1 << " 0";
    std::optional<int> o2;
    strm >> o2;
    assert(o1 == o2); // fails for certain o1 values
}

I suggest you to have a look at Boost.Optional, which does support IO.
Note that it defines its operators differently from what you propose,
and allows for the roundtrip to work.

The roundtrip property is important for serialization purposes, which is
also the primary use case for operator>>. It is not important for
diagnostic output, which is one of the use cases for operator<<. Due to
the roundtrip requirement, the output format of Boost.Optional might not
be very nice-looking in diagnostic output, which is probably why it was
not adopted by the standard.

> The proposed design has been kept simple,
> but can be extended in the future if needed.

No it can't because it would require changing the interpretation of the
input string, and that would be a breaking change.

Received on 2023-06-24 23:32:05