I'am trying to understand the example from program_options of the boost library (http://www.boost.org/doc/libs/1_38_0/doc/html/program_options/tutorial.html#id3761458)
Especially this part:
desc.add_options()
("help", "produce help message")
("compression", po::value<int>(), "set compression level")
;
what exactly is he doing here and which technique is that?
This part desc.add_options() could be a function call but how do the other () fit here? Is this some kind of operator overloading?
Thanks!
The "add_options()" function actually returns a functor, that is, an object that overrides the () operator. This means that the following function call
desc.add_options() ("help", "produce help message");
actually expands to
desc.add_options().operator()("help", "produce help message");
The "operator()" also returns a functor, so that the calls can be chained as you have shown.
Presumably add_options() returns some sort of functor that has operator() overloaded to support "chaining" (which is a very useful technique, BTW)
Overloading (...) allows you to create a class that acts like a function.
For example:
struct func
{
int operator()(int x)
{
cout << x*x << endl;
}
};
...
func a;
a(5); //should print 25
However if you make operator() return a reference to the object, then you can "chain" operators.
struct func
{
func& operator()(int x)
{
cout << x*x << endl;
return *this;
}
};
...
func a;
a(5)(7)(8); //should print 25 49 64 on separate lines
Since a(5) returns a, (a(5))(7) is more or less identical to a(5); a(7);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With