Yes, what I would like to see is the ability to stream in binary
format. By "stream" I mean overloading operator<< and >> in a way
which will only be used for binary streams. Something like:
class Vector
{
public:
int x,y,z;
};
ostream & operator<<(ostream &lhs, Vector &rhs)
{
lhs << "x: " << rhs.x << " y: " << rhs.y << " z:" << rhs.z;
return lhs;
}
binaryostream & operator<<(binaryostream &lhs, Vector &rhs)
{
lhs << rhs.x << rhs.y << rhs.z;
return lhs;
}
binaryistream & operator>>(binaryistream &lhs, Vector &rhs)
{
lhs >> rhs.x >> rhs.y >> rhs.z;
return lhs;
}
We use something like this currently in our code, but it's all
with custom classes. My question was whether there was a std
stream concept which would be a good base class to use
(binaryostream / binaryistream in the above example), and it
seems there isn't.
Sort of. My own xdrstream derive from ios (actually,
basic_ios<char>), to get the error handling and the management
of streambuf from the standard streams. ios also contains a
lot of formatting information which is irrelevant to a binary
stream, but it seems better to use it anyway, and offer exactly
the same conventions as the text streams with regards to error
handling. And of course, streambuf doesn't really care about
the format.
Logically, you'd like a stripped down ios and streambuf, without
the formatting flags and the locale, but it doesn't seem worth
the effort to implement them from scratch. (Do document,
however, that if the user provides his own filebuf, it must be
opened in binary mode, and imbued with the "C" locale. Of
course, my derived fxdrstream ensure this with the filebuf they
create.)
My feeling is that read() and write() on standard ostreams is
too error prone.
And how, since it gives you a more or less random and
undocumented binary format. That's not what they're there for;
otherwise, they'd take void* for argument, rather than charT*.
They're present for the case when you have pre-formatted text.
In the above example, assuming you're sure
that a Vector is the next piece of data in the stream, it's
pretty clear that it will serialize and unserialize from a
stream properly.
What will serialize and unserialize properly? Your code, yes.
read and write, no.
The Boost::iostream seems interesting, but it's a pretty large
library, and feels like we'd have to bend our project around
it rather than the other way around.
I've not looked at all of boost::iostream, but the parts I did
look at didn't seem to be oriented binary instead of text. It
was more a question of making it easier to extend text handling.