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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With