I have a question very similar to std::string formatting like sprintf or this question but these are very old so I dare to retry in order to collect some approaches.
I want to have a function/method which takes arguments which define a formatted string with some variables, much like printf
/sprintf
. For example it could be a method send_string(ARGS)
which would format and send a string to some receiver. E.g.:
server->send_message("value1: %d, value2: %0.3f, value3: %s", 2, 3.14, "hello world");
I know the stream concept and I know boost::format
. But I wonder what's the least verbose approach without unnecessary dependencies.
Here is what comes to my mind:
use a stream based approach - result would look like:
server->msg_out() << "value1: " << 2 << ", value2: " << 3.14 << ", value3: '" << "hello world" << "'";
This look most plausible to me but it's very verbose, it's hard to see what the output would look like. Particularly when you try to try to achieve tabular output or special formatting for real values. On the plus side you don't have any dependencies.
Use C based variable arguments. Would look like the example above which is well known and used a lot even though it's deprecated, error prone and inflexible.
Use Boost.Format
server->send_message(boost::format( "value1: %d, value2: %0.3f, value3: %s") % 2 % 3.14 % "hello world"));
or (to avoid dependencies in your API):
server->send_message( boost::str( boost::format( "value1: %d, value2: %0.3f, value3: %s") % 2 % 3.14 % "hello world")));
which seems to be the most
sprintf
-like C++ based approach. But I don't like this approach neither - it's very slow, it has a cruel syntax, it's very verbose, too and it introduces the dependency to Boost (if you don't use it already).
So currently I would decide in favor of the stream based approach but every time I use it I think to myself: there must be something more elegant!
Are there simpler approaches I didn't think of yet?