C++ – Boost Program Options Add Options Syntax

boostboost-program-optionsc

I am writing a program that uses Boost's Program Options library and I noticed the following syntax that has haunted me since I saw it:

desc.add_options()
        ("help","produce help message")
        ( /* other flag, value, description pairs here */)
;

I see that in the header, operator() is overridden, but I'm not sure how that allows this to be syntactically correct.

Secondly, is there any advantage to this syntax, compared with just calling add_options() multiple times (besides showing off the fact that you can manipulate syntax like this)?

Best Answer

The add_options member function returns an object of type options_description_easy_init. The latter has operator() overloaded to return a reference to itself. This allows you to chain the calls as you've shown in the snippet.

The difference between chaining the calls and calling add_options several times is that in the former case a single instance of options_description_easy_init is created and each time you invoke operator() on it, it adds the options to the owner (options_description). If you were to call add_options multiple times each call would create a new instance of options_description_easy_init.