Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2003-02-07 09:42:53


>From: "Jason House" <jhouse_at_[hidden]>

> Terje Slettebø wrote:
>
> > >From: "Jason House" <jhouse_at_[hidden]>
> > > I thought of one thing that might work reasonably well.
> > >
> > > How about making ++io_format< T > save the current format in a stack.
> > > and having io_format< T>-- restore the previously queuued format
> >
> > > so, then something like
> > >
> > > > > std::cout << ++io_format<char (&)[3]>("\n|","|\n","|")--
> > > > > << ++io_format<char
> > (&)[3][3]>("-------","-------","-------")--
> > > > > << board << '\n';
> > >
> > > would save and restore the formating for char(&)[3][3] and char(&)[3]
and
> > never stomp on anything else.
> >
> > In this case, it seems it saves and restores the format, before the
format
> > gets a chance to be used. In other words, the scope only covers the
state
> > saving, not the output.
>
> The idea was pre-increment and post-decrement... I wasn't sure if pre &
post
> operators work the same for classes as they do for primitive types.

Well, you can define them like that, as well. However, even in that case,
because of operator precedence, it will evaluate ++ and --, before <<, so it
would save and restore the state, before outputting.

> > std::cout << composite_save<vector<int> >() << composite_format(...) <<
v <<
> > '\n';
> >
> > An alternative is a named temporary, such as:
> >
> > composite_save<vector<int> > sentry(stream);
> >
> > // Set format and do output
>
> I think that I like your solution better :) putting it
constructor/deconstructor
> does seem better. I can't even argue that it's more typing for multi-line
> expressions...

Come to think of it, we may get the best of both worlds. :) Since the format
manipulator object also is a temporary, it can do the saving/restoring. :)

You could then do e.g:

std::cout << composite_format(...,true) << v;

This saves the format, changes it, performs output, and restores the format
in the destructor.

Likewise:

composite_format sentry(std::cout,...,true); // Save format, and set new
format. Restore in destructor.

// Do output

std::cout << composite_format(...) << v; // Doesn't save/restore the format

Alternatively, it could default to save.

> When I originally started this, I said that it was the same complaint I
have about
> io_manip... It would be neat to have a replacement/wrapper boot library
for
> io_manip.

I think the mentioned Boost I/O state savers would do that job well. That's
exactly what they are for. Have you looked at them?

Regards,

Terje


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk