I was looking at boost::format documents and just the first example made me wondering:
cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50;
What does it mean in terms of c++? I can understand call to boost::format itself, there's nothing strange there, but what's the meaning of the rest?
% "toto" % 40.23 % 50
Am I missing some special meaning '%' has in c++? What does this mean in terms of the language? I had a look into headers, but they're not particularly readable to be honest)
%
, like many operators in C++, can be overloaded for arbitrary types. If we have the expression a % b
where a
is of type A
and b
is of type B
, then C++ will look for functions compatible with the following signatures.
R operator%(const A& a, const B& b);
R A::operator%(const B& b) const;
So, presumably, boost::format
returns some custom class, on which operator%
is defined. The operator%
defined there takes this custom class and a string and produces a new instance of this custom class. Finally, when we std::cout << ...
the custom class, Boost provides an overload for that as well which prints out the string representation.
If we remove all of the operators and pretend everything is ordinary method calls, effectively this
cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50;
becomes
pipe(std::cout, percent(percent(percent(boost::format(...), "toto"), 40.23), 50));
And overload resolution on the names pipe
and percent
takes care of the rest.