|
Boost Users : |
From: Miro Jurisic (macdev_at_[hidden])
Date: 2003-12-18 10:58:36
I was trying to do the following:
class MyString;
std::istream oprator>>(std::istream&, MyString&);
std::string s1 = "Hello, World";
MyString s2 = lexical_cast <MyString> (s);
It doesn't work. The reason for it failing is:
a. the semantics of operator>>(std::istream&, MyString&) are identical to the
semantics of operator>>(std::istream&, std::string&)
b. the semantics of operator>>(std::istream&, std::string&) are to read the
stream up to the first whitespace (as per the stream locale)
c. lexical_cast uses (via lexical_stream) operator>>(std::istream&, MyString&)
to read the data into MyString
The upshot of this is that lexical_cast writes "Hello, World" to the stream (via
operator<<(std::ostream&, const std::string&)), reads off "Hello," to MyString
(via operator>>(std::istream&, MyString&)), and then throws a bad lexical_cast
after noticing there's data left on the stream.
The natural question is why it is that this works when converting to a
std::string; it seems that it should have the same problem. The answer is that
boost::detail::lexical_stream has a lexical_stream::operator>>(std::string&)
which ignores whitespace, thus working around the problem if (and only if) the
target type of the cast is std::string.
Attempting to use lexical_cast with any string type other than std::string fails
when the source data contains (non-trailing) whitespace.
This is suboptimal. I am going to try a workaround shortly, by partially
specializing lexical_stream, but that's
just a workaround. I don't see any way to do this without
a. breaking the lexical_cast abstraction barrier (as I am about to do) or
b. making the semantics of operator>>(istream&, MyString&) differ from those of
operator>>(istream&, std::string&)
I don't think either of those is the rigt answer. Is there one? Shouldn't there
be one?
Thanks,
meeroh
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net