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)?
The
add_optionsmember function returns an object of typeoptions_description_easy_init. The latter hasoperator()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_optionsseveral times is that in the former case a single instance ofoptions_description_easy_initis created and each time you invokeoperator()on it, it adds the options to the owner (options_description). If you were to calladd_optionsmultiple times each call would create a new instance ofoptions_description_easy_init.