Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost program options setting min and max value for option

Is it possible to set minimum and maximum limit of a value (suppose it is unsigned short and I need a value between 0 and 10) as I can set default value by

opt::value<unsigned short>()->default_value(5)

I want to use arguments given from variables map of program options immediately without checking each of them.

like image 276
Victor Polevoy Avatar asked Aug 28 '14 11:08

Victor Polevoy


3 Answers

I recommend a lambda (like kaveish's answer). But you can have it return a function that checks the appropriate bounds to make everything more readable.

auto in = [](int min, int max, char const * const opt_name){
  return [opt_name, min, max](unsigned short v){ 
    if(v < min || v > max){ 
      throw opt::validation_error
        (opt::validation_error::invalid_option_value,
         opt_name, std::to_string(v));
    }
  };
};

opt::value<unsigned short>()->default_value(5)
  ->notifier(in(0, 10, "my_opt"));
like image 94
Eponymous Avatar answered Nov 04 '22 10:11

Eponymous


In C++11 this can also be achieved using lambda expressions.

opt::value<unsigned short>()
  ->default_value(5)
  ->notifier(
      [](std::size_t value)
      {
        if (value < 0 || value > 10) {
          // throw exception
        }
      })

This handily keeps the validation code itself close to the call point and allows you to customize the exception easier, something like

throw opt::validation_error(
  opt::validation_error::invalid_option_value,
  "option_name",
  std::to_string(value));
like image 40
kaveish Avatar answered Nov 04 '22 10:11

kaveish


No, you cannot. All options are described here. You can check them manually, or write function, that will check them manually.

opt::value<unsigned short>()->default_value(5)->notifier(&check_function);

where check function is something like

void check(unsigned short value)
{
   if (value < 0 || value > 10)
   {
      // throw exception
   }
}

or more general

template<typename T>
void check_range(const T& value, const T& min, const T& max)
{
   if (value < min || value > max)
   {
      // throw exception
   }
}

opt::value<unsigned short>()->default_value(5)->notifier
(boost::bind(&check_range<unsigned short>, _1, 0, 10));
like image 9
ForEveR Avatar answered Nov 04 '22 08:11

ForEveR