Opened 9 years ago
Closed 8 years ago
#9603 closed Bugs (invalid)
boost::optional operator<< does the wrong thing
| Reported by: | Owned by: | Fernando Cacciola | |
|---|---|---|---|
| Milestone: | To Be Determined | Component: | optional |
| Version: | Boost 1.55.0 | Severity: | Problem |
| Keywords: | Cc: |
Description
template<class CharType, class CharTrait, class T>
inline std::basic_ostream<CharType, CharTrait>&
operator<<(std::basic_ostream<CharType, CharTrait>& out, optional<T> const& v)
{
if ( out.good() )
{
if ( !v )
out << "--" ;
else out << ' ' << *v ;
}
return out;
}
This is the wrong semantics, in my opinion. Example of the problem:
std::string s("--");
boost::optional<std::string> o;
std::cout << s << std::endl;
std::cout << o << std::endl;
prints the same, which is clearly not intended. If the optional is not engaged (no value), printing should to nothing, i.e. return the stream unmodified. Also, the ' ' character in the code above should be removed.
Change History (3)
comment:1 by , 9 years ago
comment:2 by , 8 years ago
The last requirement is invalid, the preceding space is used precisely to tell apart a valid value '--' form an invalid value. Therefore, there is a way of telling valid from invalid values. While it is a bit confusing, any adopted model would be confusing. For a detailed discussion, See here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3527.html#rationale.io Your expectation that no output should be printed for empty optional is just one of the options which is not better than any other.
comment:3 by , 8 years ago
| Resolution: | → invalid |
|---|---|
| Status: | new → closed |

It doesn't quite print the same thing. " --" is not the same as "--". I suspect that's the reason for the ' '.