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.
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"));
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));
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));
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