Following is not possible:
std::string s = boost::format("%d") % 1; // error
You have to explicitely call the method str():
std::string s = (boost::format("%d") % 1).str(); // OK
It would only be syntactic sugar, but why not just add the conversion?
It is not a very good thing if an implicit conversion can throw exceptions. Conversion to string will by default throw an exception if less arguments are fed to format
than needed.
E.g.
std::string f()
{
boost::format fmt("%d");
// forgot to feed an argument
std::string s = fmt; // throws boost::io::too_few_args
widget.set_title( fmt ); // throws boost::io::too_few_args
return fmt; // throws boost::io::too_few_args
}
Such implicit conversions make it hard to spot and analyze the parts of code that can throw exceptions. But explicit .str()
calls provide a hint of such possible exceptions, which makes life easier when ensuring the surrounding code's exception safety, as well as (in this particular case) hinting to double-check preceding code to prevent said exception from happening in the first place.