I want to add to my company's code a std::string fmtString(char const * fmt, ...); function which lets me build C++ strings from C objects in a printf way. I really liked the readability of C format strings and would like to bring it over instead of the C++ style of using operator<< or operator+.
- Is this a bad / inefficient idea?
- Does this already exist, or is C-style building of C++ strings already easy without a custom method?
- What's the best way to implement such a method? It would have to be thread safe.
EDIT: This needs to work without C++11, but I'm still interested in C++11 solutions to the problem!
is a C++11 signature for such a function. This allows run time type safety and controlled failure.
Do not use C style VA-args, as that makes any kind of sensible failure impossible (type checking, arg count checking, etc).
Parsing said
string_viewwill take time at runtime, but other than that there is no fundamental inefficiency here. Aconstexprparser that turns a string of characters into a parsed formatter may be a good idea, possibly a string-literal.boosthas many C-style C++ formatters.You'll want to walk the format string, looking for format commands. Dump the non-format text as you go along. At each format command, switch on it and consume one or more
Argsinto an error-generating consumer of the type you expect.An example of a
%dconsumer would be:then in the parsing code, when you run into
%d, you do:after you parse each format command, you recurse on your print function with less arguments and the tail end of the format string.
Handling more complex formatting (like
%.*f) is naturally trickier. It could help if you request that "formatting bundle" arguments are grouped in theArgssomehow.