olooney olooney - 2 months ago 29
C++ Question

What is boost::program_options::notify() for?

This question is about the C++ Boost program_options library.

All the tutorials are very clear that I should call

notify()
on my completed variable map, but I'm not sure what this is actually doing for me. Commenting it out didn't seem to have any effect, and the documentation didn't go into much detail:

http://www.boost.org/doc/libs/1_47_0/doc/html/boost/program_options/notify.html

Other sources suggest that it runs "user-defined" functions. If so, how are those functions registered and what do they do? Might they throw exceptions?

Answer

notify() is a member function of value_semantic. It is a hook that is provided so that, once the final value of an option is determined, any action that should be taken with that option can be done automatically and be encapsulated in its own function. This prevents code from having one long function that acts on each of the options. As the possible options grow, that kind of procedural code can get unwieldy.

You can see an example of setting a notify function in the Boost manual:

options_description desc;
desc.add_options()
    ("compression", value<int>()->default_value(10), "compression level")
    ("email", value< vector<string> >()
        ->composing()->notifier(&your_function), "email")
    ;

These declarations specify that default value of the first option is 10, that the second option can appear several times and all instances should be merged, and that after parsing is done, the library will call function &your_function, passing the value of the "email" option as argument.

Comments