Boost logo

Boost :

From: Roland Schwarz (roland.schwarz_at_[hidden])
Date: 2008-02-29 10:32:56

Surprisingly I was not able to find on the net
code that would give me a smart way to indent
a stream. So I wrote a little filter based on
the boost iostreams library.

My first attempt was:

boost::iostreams::filtering_ostream out;
indent_filter ind(4);

However trying to control it via e.g. ind.out() turns out to be problematic
interface since,
1) out.push() takes a copy of ind
2) the interface is suboptimal.

With my attached example it is possible to:

#include "indent.hpp"


boost::iostreams::filtering_ostream out;


And use it like so:

out << "Hello Filter!\n"
    << indent_in
    << "this is\n"
    << "indented\n"
    << indent_out
    << "until here\n"

Which will result in output:

Hello Filter!
  this is
until here

The state is stored in the ios base class of the stream,
by way of the pword mechanism.
Consequently the filter stream even may be downcast to
a basic_ostream, and the indenter will still work.
E.g. with out defined as above:


void foo(std::ostream& out)
    out << indent_in
        << "out is a downcast filter_stream\n"
        << indent_out
        << "end of indentation\n"

If you want to try it out, you just need to include the
header indent.hpp.

If someone thinks the snippet is usable either as an example
for the iostreams library or the filter streams manipulator
idea is worth generalizing to make it usable for other filters
too, I would be glad to hear from you.

  _  _  | Roland Schwarz
 |_)(_  | aka. speedsnail
 | \__) | mailto:roland.schwarz_at_[hidden]

Boost list run by bdawes at, gregod at, cpdaniel at, john at