scd*_*dmb 19 c++ boost-program-options
有没有办法为参数设置一组允许的输入变量?例如,参数"arg"只能包含像"cat"和"dog"这样的字符串值.
Rob*_*edy 24
您可以使用自定义验证器功能.为您的选项定义一个不同的类型,然后重载该validate类型的函数.
struct catdog {
catdog(std::string const& val):
value(val)
{ }
std::string value;
};
void validate(boost::any& v,
std::vector<std::string> const& values,
catdog* /* target_type */,
int)
{
using namespace boost::program_options;
// Make sure no previous assignment to 'v' was made.
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.
std::string const& s = validators::get_single_string(values);
if (s == "cat" || s == "dog") {
v = boost::any(catdog(s));
} else {
throw validation_error(validation_error::invalid_option_value);
}
}
Run Code Online (Sandbox Code Playgroud)
从该代码抛出的异常与针对任何其他无效选项值抛出的异常没有区别,因此您应该已经准备好处理它们.
使用特殊选项类型而不是string在定义选项时:
desc.add_options()
("help", "produce help message")
("arg", po::value<catdog>(), "set animal type")
;
Run Code Online (Sandbox Code Playgroud)
我已经编写了一个演示使用此代码的实例.
一个非常简单的方法是将"animal"作为普通字符串,并在通知您测试并在需要时抛出.
if (vm.count("animal") && (!(animal == "cat" || animal == "dog")))
throw po::validation_error(po::validation_error::invalid_option_value, "animal");
Run Code Online (Sandbox Code Playgroud)