Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this programming technique? (Boost Library)

Tags:

c++

boost

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!

like image 670
Herrbert Avatar asked Nov 29 '22 12:11

Herrbert


2 Answers

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.

like image 189
Martin Cote Avatar answered Dec 09 '22 10:12

Martin Cote


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

like image 20
v3. Avatar answered Dec 09 '22 12:12

v3.