有没有办法为参数设置一组允许的输入变量?例如参数“arg”只能有“cat”和“dog”之类的字符串值。
最佳答案
您可以使用 custom validator特征。为您的选项定义一个不同的类型,然后在该类型上重载 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);
}
}
该代码引发的异常与任何其他无效选项值引发的异常没有什么不同,因此您应该已经准备好处理它们。
当你定义你的选项时,使用特殊的选项类型而不是仅仅string
:
desc.add_options()
("help", "produce help message")
("arg", po::value<catdog>(), "set animal type")
;
关于c++ - Boost 程序选项允许输入值集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8820109/