[Effective-cpp] Item 2: The String Formatters of Manor Farm, Part 1: sprintf

Terje Slettebø tslettebo at broadpark.no
Sun Oct 31 04:29:54 EST 2004


> >> From: "White Wolf" <wolof at freemail.hu>
> >
> > With something like Boost.Format
> > (http://www.boost.org/libs/format/index.html), you can get
> > both the advantage of a format string, and, unlike (s)printf,
> > type safety, works with any type having an output stream
> > operator defined, and being generic (even though the syntax
> > may seem a little odd). You can also "reuse" an argument
> > several times in the format string:
> >
> > std::cout << boost::format("%1% + %2% = %3%") % 10 % 20 %
> > (10+20) << "\n"; // Prints "10 + 20 = 30"
>
> Does is scale to user defined types?  Can I say I want to print my Widget,
> in short-log mode?  And then later if I want print it in detailed-log
more?

Good question. I guess that it would work the same way as if you used it in
stream output directly. That is, the following should be roughly equivalent
to the above example:

std::cout << 10 << " + " << 20 << " = " << 10+20 << "\n";

Following from this, if your Widget class uses stream-stored formatting
(iword/pword), set using manipulators, then it should be possible to set the
manipulator before the call to format(). However, I guess you have to use a
separate format() call for each stream formatting:

std::cout << short_log << format("...") % ... % ... % ...;
std::cout << long_log << format("...") % ... % ... % ...;

Regards,

Terje




More information about the Effective-cpp mailing list