5

Is there a simple way to check if the argument of an option is inside a set of predefined choices? "Simple" here means without defining an ad-hoc class.

Suppose I have the option --myoption which must have value "myvalue1" or "myvalue2"

For example in python is really easy with choices option in optparse

reuben
  • 3,360
  • 23
  • 28
Ruggero Turra
  • 16,929
  • 16
  • 85
  • 141
  • 1
    Wouldn't this just be comparing strings? Assuming they are both `std::string`, you could do `if ((arg == myvalue1) || (arg == myvalue2))`. – Jesse Good Jul 02 '12 at 00:00
  • sure, it works, but I need something more integrated in `program-options` (for example it can change the help message), for example working with non-string – Ruggero Turra Jul 02 '12 at 00:07
  • You might want to explain more about what you want to do, it is unclear. – Jesse Good Jul 02 '12 at 00:22
  • @JesseGood: very simple, I want if user types `--myoption myvalue3` the program should raise an exception. – Ruggero Turra Jul 02 '12 at 08:04
  • possible duplicate of [Boost program options allowed set of input values](http://stackoverflow.com/questions/8820109/boost-program-options-allowed-set-of-input-values) – Ruggero Turra Mar 28 '13 at 19:40
  • possible duplicate of [Sets of mutually exclusive options in boost program options](http://stackoverflow.com/questions/15577107/sets-of-mutually-exclusive-options-in-boost-program-options) – Uli Köhler Mar 14 '15 at 18:28
  • Possible duplicate of https://stackoverflow.com/q/15577107/2597135 – Uli Köhler Mar 14 '15 at 18:28

1 Answers1

0

As I've just realized, you can define two mutually exclusive options simply defining a small function as explained in real.cpp. For example, you can specify two conflicting 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()

Checking that --myoption is equal to myvalue1 or myvalue2 then becomes just a matter of a function call.

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