Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost Program Options dependent options

Is there any way of making program options dependent on other options using boost::program_options?

For example, my program can accept the following sample arguments:

wifi --scan --interface=en0
wifi --scan --interface=en0 --ssid=network
wifi --do_something_else

In this example, the interface and ssid arguments are only valid if they are accompanied by scan. They are dependent on the scan argument.

Is there any way to enforce this automatically with boost::program_options? It can of course be implemented manually but it seems like there must be a better way.

like image 966
Conor Taylor Avatar asked Jul 10 '16 06:07

Conor Taylor


1 Answers

You can define two dependent options simply defining a small function as explained in real.cpp. For example, you can specify two depending (or conflicting) options defining a option_dependency() function:

void option_dependency(const boost::program_options::variables_map & vm,
    const std::string & for_what, const std::string & required_option)
{
  if (vm.count(for_what) && !vm[for_what].defaulted())
    if (vm.count(required_option) == 0 || vm[required_option].defaulted())
      throw std::logic_error(std::string("Option '") + for_what 
          + "' requires option '" + required_option + "'.");
}

and then calling

option_dependency (vm, "interface", "scan");
option_dependency (vm, "ssid", "scan");

right after boost::program_options::store()

Pay attention that this function option_dependency is one-way only. In this case ssid requires scan option, but not the other way around.

like image 105
malat Avatar answered Nov 06 '22 04:11

malat