Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

c++ - Boost program options allowed set of input values

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
  }
}

The exceptions thrown from that code are no different from the exceptions thrown for any other invalid option value, so you should already be prepared to handle them.

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")
;

I've composed a live example demonstrating use of this code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...