|
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);
out.push(ind);
out.push(std::cout);
However trying to control it via e.g.
ind.in() ind.out() turns out to be problematic
interface since,
1) out.push() takes a copy of ind
2) the interface ind.in() is suboptimal.
With my attached example it is possible to:
#include "indent.hpp"
...
boost::iostreams::filtering_ostream out;
indent_filter::push(out,2);
out.push(std::cout);
...
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
indented
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:
...
foo(out);
...
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] ________| http://www.blackspace.at
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk