【发布时间】:2014-03-20 13:30:01
【问题描述】:
我正在尝试为程序增强选项编写自己的验证函数。但是,我得到:
" 在抛出 '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>());
我将不胜感激;>
【问题讨论】:
-
如果你让你的样本独立(sscce.org)你会发现你得到了更多高质量的答案。我并不总是有时间做额外的工作。我在 90% 的答案中都在 Coliru 上运行了样本。
标签: c++ boost boost-program-options