tags:

views:

279

answers:

2

Hi,

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 technic 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!

+12  A: 

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.

Martin Cote
+10  A: 

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);.

v3
Nice answer. If you and/or anyone could expand on why chaining is "very useful", that would make this complete...
mikeh