Boost Program Options dependent options
Asked Answered
S

1

11

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.

Streetwalker answered 10/7, 2016 at 6:2 Comment(1)
I suspect there is no way of telling boost::po to do that: take a look at the public APIs for value_semantic (the po::value<stuff>() bit) and option_descriptionLaudianism
T
7

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.

Tigre answered 28/4, 2017 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.