IOStreams & custom formatting objects
by Thijs van den Berg
Recently I had to add support for multiple output formats of some C++ data structures that I was generating. Something along the lines of writing a matrix data structure to a file in either
- binary format,
- comma separate file (csv),
- HTML tables,
- ...
My idea was to implement a stream syntax ala setw() which is used to set the field width for the next stream insertion operation.
std::cout << std::setw(2) << d;
The nice thing about this approach is that the formatting details are stored in the stream, -not in all of the objects-. For specifying file types, that would be the best place to store that information. All object can query the formatting information from the stream, and serialize themselves in the corresponding format. The solution I ended up with looks like this
std::cout << my_format::HTML << some_object;
std::cout << another_object;
Attaching custom meta data to a stream
Central to this approach is to use ios_base::xalloc() to get a index to a storage location which will be available in all streams to write and read data (an integer) to/from..
static const int iword_index = std::ios_base::xalloc();
The above statement gives us a index that we name iword_index, and which can be user to store...
std::ostream os1,os2;
os1.iword(iword_index) = 3;
os2.iword(iword_index) = 17;
and retrieve values that are attached to streams
switch ( os1.iword(iword_index) )
{
case 3: os1 << "format number 3:" << ...
}
























Recent Forum Discussions