September 14, 2007

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:" << ...
}

C(omp) Search


WWW
compplusplus.com

C(omp) Community

Could this be you? Thijs van den Berg Dr. Jörg Kienitz Bjarne Stroustrup Dr. Egor Kraev Daniel Duffy Andrea Germani Umberto Cherubini Luigi Ballabio

More Members

Meet the Editorial Team



C(omp) Feeds


Want to know when new posts and features are made available? Sign up to receive email notifications by entering your email address:

Delivered by FeedBurner



Any Comments?

Send in questions for our authors and bloggers: comp@wiley.co.uk



C(omp) Events

1) 13-15 November: Quant Invest 2007
Russell Hotel, London
Key speakers include Sushil Wadhhwani, Paul Wilmott and Deborah Fuhr...

2) 30 November: CCCP Mathematical Finance Conference
Princeton University
Speakers include Paul Glasserman, Peter Carr and Rama Cont.

3) 10-14 December: Risk Minds 2007
President Wilson, Geneva

4) 12-15 December: Quantitative Methods in Finance
Manly Pacific Hotel
Sydney, Australia
Speakers include Mark Joshi

5) January 2008: Distance Learning for Financial Engineers
Computational and Quantitative Finance in C++
Datasim Education BV


Recent Forum Discussions


C(omp) Calendar

June 2008
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30