gpt4 book ai didi

c++ - boost program_options 自定义验证

转载 作者:行者123 更新时间:2023-11-30 05:14:06 25 4
gpt4 key购买 nike

我正在尝试了解 program_options 自定义验证,以便将 python 代码转换为 c++ 代码。
无论如何
我在示例中读到我必须重载验证函数
我试图在 boost program_options 文件中找到原始函数,但没有成功
任何人都可以告诉我原始验证函数在哪里,我会过度加载它
这是一个愚蠢的问题,但我想知道它是如何在默认情况下进行验证的,以了解验证的概念以及它是如何完成的
提前致谢

最佳答案

扩展我的单行评论,我总是发现 boost::program_options 在参数验证方面有点不足。

因此,我发现为每个选项类型编写自定义类通常更容易。通常 program_options 使用 operator>> 来解码选项值,因此如果您覆盖它,您将有机会抛出 program_options 识别的异常。如果使用嵌套异常,则可以打印非常详细的错误诊断信息。

例子:

#include <boost/program_options.hpp>
#include <iostream>
#include <iomanip>
#include <sstream>

namespace po = boost::program_options;

// a custom option type
struct foo_or_bar {
std::string value;

// self-describing
static constexpr const char *option_name() { return "foo"; }

static constexpr const char *description() { return "single option only. value must be either foo or bar"; }

// check the value and throw a nested exception chain if it's wrong
void check_value() const
try {
if (value != "foo" and value != "bar") {
std::ostringstream ss;
ss << "value must be foo or bar, you supplied " << std::quoted(value);
throw std::invalid_argument(ss.str());
}
}
catch (...) {
std::throw_with_nested(po::validation_error(po::validation_error::invalid_option_value, option_name()));

}

// overload operators
friend std::istream &operator>>(std::istream &is, foo_or_bar &arg) {
is >> arg.value;
arg.check_value();
return is;
}

friend std::ostream &operator<<(std::ostream &os, foo_or_bar const &arg) {
return os << arg.value;
}

};

// test
void test(int argc, const char **argv) {
foo_or_bar my_foo;

po::options_description desc("test options");
desc.add_options()
(foo_or_bar::option_name(), po::value(&my_foo), foo_or_bar::description());

po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);


std::cout << "foo is " << my_foo << std::endl;
}

void print_exception(const std::exception& e, int level = 0)
{
std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n';
try {
std::rethrow_if_nested(e);
} catch(const std::exception& e) {
print_exception(e, level+1);
} catch(...) {}
}

int main() {
{
std::vector<const char *> test_args = {
"executable_name",
"--foo=bar"
};
test(test_args.size(), test_args.data());
}

try {
std::vector<const char *> test_args = {
"executable_name",
"--foo=bob"
};
test(test_args.size(), test_args.data());
}
catch (std::exception const &e) {
print_exception(e);
}
}

预期输出:

foo is bar
exception: the argument for option '--foo' is invalid
exception: value must be foo or bar, you supplied "bob"

关于c++ - boost program_options 自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572862/

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