Increase min and max program parameter settings for option

Is it possible to set the minimum and maximum limit of the value (suppose it is unsigned short and I need a value from 0 to 10), since I can set the default value to

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

I want to use the arguments given from the map of variable parameters of the program, without checking each of them.

+7
c ++ boost max minimum boost-program-options
source share
3 answers

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

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

where the 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)); 
+7
source share

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 conveniently holds the verification code directly from the dial peer and allows you to simplify the configuration of the exception, for example

 throw opt::validation_error( opt::validation_error::invalid_option_value, "option_name", std::to_string(value)); 
+7
source share

I recommend lambda (e.g. kaveish's answer ). But you can return a function to it that checks the corresponding boundaries 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")); 
+7
source share

All Articles