”的实例后调用终止 what(): boost-6ren">
gpt4 book ai didi

c++ - boost 程序选项和验证功能

转载 作者:太空宇宙 更新时间:2023-11-04 13:53:37 25 4
gpt4 key购买 nike

我正在尝试为程序 boost 选项编写自己的验证函数。但是,我得到:

"在抛出“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>());

如有任何建议,我将不胜感激;>

最佳答案

在定义选项时使用特殊选项类型而不是字符串:

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

关于c++ - boost 程序选项和验证功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22534499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com