Re: [Boost-bugs] [Boost C++ Libraries] #2659: optional_io insertion operator assumes presence of whitespace on stream

Subject: Re: [Boost-bugs] [Boost C++ Libraries] #2659: optional_io insertion operator assumes presence of whitespace on stream
From: Boost C++ Libraries (noreply_at_[hidden])
Date: 2009-02-04 21:15:32


#2659: optional_io insertion operator assumes presence of whitespace on stream
--------------------------------------------------------+-------------------
  Reporter: Andrew Troschinetz <ast_at_[hidden]> | Owner: fcacciola
      Type: Bugs | Status: new
 Milestone: Boost 1.38.0 | Component: optional
   Version: Boost 1.37.0 | Severity: Problem
Resolution: | Keywords:
--------------------------------------------------------+-------------------

Comment(by Andrew Troschinetz <ast_at_[hidden]>):

 I think I understand why optional_io is coded the way it is. I also think
 it can be improved upon.

 For example:

 {{{
     istringstream sin (" 1 this 5.5 is a test -3.2 a");
     optional<double> token;
     while (sin >> token) cout << token.get_value_or
 (numeric_limits<double>::quiet_NaN ()) << endl;
 }}}

 This will print out 1 and then exit the loop, but I think it would be
 nicer, and less surprising if it printed out:

 {{{
     1
     nan
     5.5
     nan
     nan
     nan
     -3.2
     nan
 }}}

 This can be accomplished by changing operator>>() to the following:

 {{{
     if (in)
         {
             std::string token;
             in >> token;

             if (!in)
             {
                 v = optional<T> ();
                 return in;
             }

             std::istringstream sin (token);
             T x;
             if (sin >> x) v = x;
             else v = optional<T> ();
         }
         else
         {
             v = optional<T> ();
         }
     return in;
 }}}

 We protect the istream from its failbit getting set by first extracting
 the next token as a string, which is sure to succeed if there is anything
 at all on the stream.

 This way, we don't set the failbit on the istream just because we fail to
 extract a value for our optional type. I think this fits with the
 semantics of optional types because it's a valid state for an them to be
 uninitialized, unlike just about any other type.

 This change also nicely fixes the problem I initially reported.

-- 
Ticket URL: <https://svn.boost.org/trac/boost/ticket/2659#comment:2>
Boost C++ Libraries <http://www.boost.org/>
Boost provides free peer-reviewed portable C++ source libraries.

This archive was generated by hypermail 2.1.7 : 2017-02-16 18:49:59 UTC