c++ - Boost 程序选项允许输入值集

标签 c++ boost-program-options

有没有办法为参数设置一组允许的输入变量?例如参数“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")
;

我写了一个 live example demonstrating use of this code .

关于c++ - Boost 程序选项允许输入值集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8820109/

相关文章:

c++ - boost::program_options 位置选项

c++ - 无法让我的递归函数正确计算字符串中的字母 (c++)

c++ - "D3DX11CreateShaderResourceViewFromFile"让它工作或寻找替代品

c++ - 在 iOS Xcode 项目中运行 C++ 库时出错

c++ - 如何在 boost 程序选项中有一个可选的选项值?

c++ - 使用 boost::program_options 解析配置文件

c++ - 函数调用后头文件导致原数组出现问题

C++ cwchar 错误

c++ - 是否可以在 CLI 解析完成后添加 boost program_options 和参数?