In the code below, I used program options to read parameters from command-line or file. In addition, options can be set programatically at runtime through ConfigProxy::setConfig
po::options_description desc("Allowed options");
desc.add_options()
...
("compression", po::value<int>(), "set compression level");
po::variables_map vm;
class ConfigProxy
{
template< typename T>
void setConfig( const std::string key, const T value ){
... // check if the key exists in variable map "vm"
// key exists, set the value
runtimeConfig[key] = po::variable_value( boost::any(value), false);
}
po::variable_value& operator[] (const std::string key) const{
...
// if exists in runtimeConfig return the value in runtimeConfig
// of type program_options::variable_value
...
// else return value in variable map "vm"
}
std::map<std::string, boost::program_options::variable_value> runtimeConfig;
}
through ConfigProxy, the option value is retrieved
if( vm.count("compression") ){
int value = proxyConfig["compression"].as<int>();
...
}
However, if the "compression" option value provided by the user is in wrong type, for example
configProxy.setConfig("compression", "12" );
...
int value = configProxy["compression"].as<int>(); // was set as string
then exception is thrown
what(): boost::bad_any_cast: failed conversion using boost::any_cast
The exception clearly shows the type cast problem. But the message seems not so helpful to users for finding out which option is responsible for the error.
Is there a better way to inform users about this type of error, instead of throwing bad_any_cast exception?
----- Edit --------------------------
Thanks to Luc Danton and Tony, I have found how Program options shows the errors.
void validate(boost::any& v,
const std::vector< std::basic_string<charT> >& xs,
T*, long)
{
validators::check_first_occurrence(v);
std::basic_string<charT> s(validators::get_single_string(xs));
try {
v = any(lexical_cast<T>(s));
}
catch(const bad_lexical_cast&) {
boost::throw_exception(invalid_option_value(s));
}
}
I think, by implementing the logic, I can get rid of the bad_any_cast exception.