19

My program (prog.exe) supports the following four flags: -P, -p , -b and -s. However:

  • -b and -p must be specified together, constitute a set, and have numeric values e.g. -b 42
  • -s cannot be specified with the above set, and vice versa
  • -P is mandatory in both cases

As such prog.exe can only be run as either

prog.exe -P -s 

or

prog.exe -P -b -42 -p 8

Is there a way to specify the above sets of mutually exclusive command line options in boost program options?

Olumide
  • 5,397
  • 10
  • 55
  • 104
  • 1
    That's part of logic to implement in the (obligate) `parseOptions()` method of a `boost::program_options` client application IMHO. – πάντα ῥεῖ Mar 22 '13 at 18:10
  • 2
    I've come along such situations, and usually map them to some 'program execution mode' enum options. I first lookup option settings for this and after determining it, proceed with the specific options ... – πάντα ῥεῖ Mar 22 '13 at 18:15

1 Answers1

26

You should start with a few tutorials [1][2] to understand how boost::program_options works.

Then, you can define two mutually exclusive options simply defining a small function as explained in real.cpp. For example, you can specify two conflicting (or depending) options defining a conflicting_options() function:

void conflicting_options(const boost::program_options::variables_map & vm,
                         const std::string & opt1, const std::string & opt2)
{
    if (vm.count(opt1) && !vm[opt1].defaulted() &&
        vm.count(opt2) && !vm[opt2].defaulted())
    {
        throw std::logic_error(std::string("Conflicting options '") +
                               opt1 + "' and '" + opt2 + "'.");
    }
}

and then calling

conflicting_options (vm, "quiet", "verbose");

right after boost::program_options::store()

I still don't understand if it's possible to define two mutually exclusive positional options, but that should be another question.

Avio
  • 2,700
  • 6
  • 30
  • 50
  • 3
    In my opinion it is so much boilerplate code! Why wouldn't boost support mutually exclusive groups like python's argparse does it? – Asalle Jan 31 '17 at 15:06
  • Python is almost always more concise than C++, it's always been. C++11/14/17 are moving forward in this direction, but the pace is slow. – Avio Feb 09 '17 at 12:04