Why boost::format cannot be converted directly to std::string?

mr_georg picture mr_georg · Oct 18, 2012 · Viewed 8.9k times · Source

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?

Answer

BigBoss picture BigBoss · Oct 18, 2012

I think the reason for this is same as std::stringstream, in that context you should also use .str() to convert the stream to string and same for boost::formatter and the reason is as:

std::string s1 = "Hello ", s2 = "World";
format("%s.") % s1 + s2;

Now if boost::formatter was implicitly convertible to std::string then it produce "Hello .World", because format("%s.") % s1 will be converted to "Hello ." and then it will be implicitly converted to std::string and use operator+ to add it with s2, but probably most programmers want to have "Hello World." and that will be a source of error an confusion. But in the case that no implicit conversion exist compiler will generate error for this(because there is no operator+ for boost::formatter and std::string) and for you to correct it either as format("%s.") % (s1 + s2) or str( format("%s.") % s1 ) + s2