Copied from SOCopied from SO. (Looking at the the FAQ, I'd say it is on topic here.)
- A purpose — a task to accomplish, a user story
➔ Make iostreams
less verbose to use and prevent errors wrt. stickiness / non stickiness of flags.
- Some objective requirements — a minimum set of features
➔ Provide a wrapper function for each of the format flags as well as the fill, precision and width options.
Since raw use of the iomanip stream modifiers is a) verbose and b) error prone (sticky vs. non-stickysticky vs. non-sticky, etc.), for user defined types, all that stuff can be hidden in the default operator<<
... as shown here, for exampleshown here, for example.
However, when formatting built-in types (even from within a user defined operator), it would be much more convenient (IMHO) to use an approach similar to std::quoted
(beware C++14), where the data is wrapped in a function call that returns a temporary object that sets + resets the appropriate flags.
Essentially, instead of writing:
std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n";
you would hypothetically write:
using namespace shorter;
std::cout << precis(2, fixed(1.234556)) << "\n";
As the example shows, combination of flags could get tricky and I'm sure the devil is in the details, so I was wondering whether there is any prior art / exiting helper library that tries to address "chevron hell". :-)
- Is there any existing library addressing this?
- What are the technical pitfalls here, if one wants to come up with a set of helpers oneself?
Specifically, this question is not about any kind of "type safe format string" (like Boost.Format offers).
I'm also not asking for a "best" library, I'm asking about any library doing this for normal ostreams. (Because I was not able to find any.)
For example, the write API of C++ Format does something like this, but it doesn't do it for std::iostreams, but for the library's "stream" type:
MemoryWriter out;
out << pad(hex(0xcafe), 8, '0');