Boost程序选项允许设置输入值 [英] Boost program options allowed set of input values

查看:236
本文介绍了Boost程序选项允许设置输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为参数设置一组允许的输入变量?例如,参数arg只能包含cat和dog等字符串值。

Is there a way to set an allowed set of input variables for parameters? For example parameter "arg" can have only string values like "cat" and "dog".

推荐答案

a href =http://www.boost.org/doc/libs/1_48_0/doc/html/program_options/howto.html#id2445062 =nofollow> 自定义验证器 功能。为您的选项定义不同类型,然后重载该类型的 validate 函数。

You can use the custom validator feature. Define a distinct type for your option, and then overload the validate function on that type.

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

Use the special option type instead of just string when you define your options:

desc.add_options()
  ("help", "produce help message")
  ("arg", po::value<catdog>(), "set animal type")
;

我组成了一个实例演示如何使用此代码

这篇关于Boost程序选项允许设置输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆