在下面的代码中,我使用程序选项从命令行或文件中读取参数。此外,可以在运行时通过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;
}
通过ConfigProxy,取回option值
if( vm.count("compression") ){
int value = proxyConfig["compression"].as<int>();
...
}
但是,如果用户提供的“压缩”选项值类型错误,例如
configProxy.setConfig("compression", "12" );
...
int value = configProxy["compression"].as<int>(); // was set as string
然后抛出异常
what(): boost::bad_any_cast: failed conversion using boost::any_cast
该异常清楚地显示了类型转换问题。但是该消息似乎对用户找出导致错误的选项没有太大帮助。
有没有更好的方法来通知用户这种类型的错误,而不是抛出bad_any_cast异常?
- - - 编辑 - - - - - - - - - - - - -
感谢 Luc Danton 和 Tony,我发现了程序选项如何显示错误。
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));
}
}
我认为,通过实现逻辑,我可以摆脱 bad_any_cast 异常。