我正在尝试为程序提升选项编写自己的验证函数。但是,我得到了:
" 在抛出' boost :: exception_detail :: clone_impl>'的实例后终止调用 what():boost :: bad_any_cast:使用boost :: any_cast进行转换失败 "
我甚至在stackoverflow上看过类似的帖子,但我无法正常工作......下面是我的代码。嗯,我想,不知怎的,我不得不使用lexical_cast并自己写这个演员,但我失败了......
在我的一个头文件中:
enum class LogSeverityLevel : std::int8_t { E_LOG_TRACE = 0,
E_LOG_DEBUG,
E_LOG_INFO,
E_LOG_WARN,
E_LOG_ERROR};
在我的main.cpp文件中:
void validate(boost::any& v,
const std::vector<std::string>& values,
LogSeverityLevel*, int)
{
// Make sure no previous assignment to 'a' was made.
po::validators::check_first_occurrence(v);
// Extract the first string from 'values'. If there is more than
// one string, it's an error, and exception will be thrown.
const std::string& s = po::validators::get_single_string(values);
const std::string& s_capitalized = boost::to_upper_copy(s);
if (s_capitalized== "ERROR") {
v = boost::any(LogSeverityLevel::E_LOG_ERROR);
} else if (s_capitalized == "WARN") {
v = boost::any(LogSeverityLevel::E_LOG_WARN);
} else if (s_capitalized == "INFO") {
v = boost::any(LogSeverityLevel::E_LOG_INFO);
} else if (s_capitalized == "DEBUG") {
v = boost::any(LogSeverityLevel::E_LOG_DEBUG);
} else if (s_capitalized == "TRACE") {
v = boost::any(LogSeverityLevel::E_LOG_TRACE);
} else {
throw po::validation_error(po::validation_error::invalid_option_value);
}
}
然后,稍后在main.cpp中:
desc.add_options()
("help,h", "print this help")
("version,v", "show application version")
("log-level", po::value<std::string>()->default_value("DEBUG"), "set log level")
;
然后:
if (vm.count("log-level")) {
setLogSeverityLevel(vm["log-level"].as<LogSeverityLevel>());
我会感谢任何建议;&gt;
答案 0 :(得分:0)
在定义选项时使用特殊选项类型而不是字符串:
desc.add_options()
("help,h", "print this help")
("version,v", "show application version")
("log-level", po::value<LogSeverityLevel>()
->default_value(LogSeverityLevel::E_LOG_DEBUG, "DEBUG"), "set log level")
;