Simplest way to mix sequences of types with iostreams?
Posted
by Kylotan
on Stack Overflow
See other posts from Stack Overflow
or by Kylotan
Published on 2010-03-24T10:52:34Z
Indexed on
2010/03/24
11:23 UTC
Read the original article
Hit count: 231
I have a function void write<typename T>(const T&)
which is implemented in terms of writing the T object to an ostream, and a matching function T read<typename T>()
that reads a T from an istream. I am basically using iostreams as a plain text serialisation format, which obviously works fine for most built-in types, although I'm not sure how to effectively handle std::strings just yet.
I'd like to be able to write out a sequence of objects too, eg void write<typename T>(const std::vector<T>&)
or an iterator based equivalent (although in practice, it would always be used with a vector). However, while writing an overload that iterates over the elements and writes them out is easy enough to do, this doesn't add enough information to allow the matching read operation to know how each element is delimited, which is essentially the same problem that I have with a single std::string.
Is there a single approach that can work for all basic types and std::string? Or perhaps I can get away with 2 overloads, one for numerical types, and one for strings? (Either using different delimiters or the string using a delimiter escaping mechanism, perhaps.)
© Stack Overflow or respective owner