2

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)

Roman
  • 1,396
  • 4
  • 15
  • 39

1 Answers1

3

%, 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.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • 2
    oooooooooooooh! simple. Although I have to mention that this is the last operator I could thought about in that way. I've kind of failed into the trap of forgetting that this is just another operator. Something you never really do in real life. I'll leave it here just for the additional reading -- Which Operators Cannot Be Overloaded https://isocpp.org/wiki/faq/operator-overloading#overloadable-opers – Roman Jul 20 '22 at 07:51
  • @Roman you'll be surprised to see the useless comma operator due to the low precedence can be [overloaded in clerver ways](https://stackoverflow.com/q/5602112/995714). And C++20 made comma operator deprecated inside `[]` to prepare for more useful overloads in the future – phuclv Jul 20 '22 at 15:32