50

I have two related questions:

  1. What is the simplest way to allow passing a series of values, using Boost Program Options? My aim is to avoid prog --opt 1 --opt 2 --opt 3 and have prog --opt 1 2 3 instead.

  2. What is the simplest way to have an option that takes exactly two numbers, e.g. prog --opt 137 42?

(I don't need any "free" program parameters.)

4

2 回答 2

46

这是一个迟到的答案,但我希望它对某人有所帮助。您可以轻松地在项目 #1 中使用相同的技术,除了您需要对向量中的项目数量添加另一个验证:

从 rcollyer 的例子:

namespace po = boost::program_options;
po::option_descriptions desc("");

desc.add_options()
 ("opt", po::value<std::vector<int> >()->multitoken(), "description");

po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm); 

vector<int> opts;
if (!vm["opt"].empty() && (opts = vm["opt"].as<vector<int> >()).size() == 2) {
  // good to go
}
于 2012-12-31T18:37:23.357 回答
36

对于第一部分,这应该有效

namespace po = boost::program_options;
po::option_descriptions desc("");

desc.add_options()
 ("opt", po::value<std::vector<int> >()->multitoken(), "description");

第二部分,需要更多的工作。该函数po::value返回一个po::typed_value< T, charT >,您必须在其上覆盖多个函数的行为,如下所示

template< typename T, typename charT = char >
class fixed_tokens_typed_value : public po::typed_value< T, charT > {
   unsigned _min, _max;

   typedef po::typed_value< T, charT > base;

 public:

   fixed_tokens_typed_value( T * t, unsigned min, unsigned max ) 
     : _min(min), _max(max), base( t ) {
       base::multitoken();
   }

   virtual multi_typed_value* min_tokens( unsigned min ) {
       _min = min;
       return *this;
   }
   unsigned min_tokens() const {return _min;}

   virtual multi_typed_value* max_tokens( unsigned max ) {
       _max = max;
       return *this;
   }
   unsigned max_tokens() const {return _max;}

   base* zero_tokens() {
       _min = _max = 0;
       base::zero_tokens();
       return *this;
   }
}

需要伴随的

template< typename T >
fixed_tokens_typed_value< T > 
fixed_tokens_value(unsigned min, unsigned max) {
    return fixed_tokens_typed_value< T >(0, min, max ); }

template< typename T >
fixed_tokens_typed_value< T > 
fixed_tokens_value(T * t, unsigned min, unsigned max) {
    fixed_tokens_typed_value< T >* r = new
                   fixed_tokens_typed_value< T >(t, min, max);
    return r; }

然后

desc.add_options()
 ("opt", po::fixed_tokens_value<std::vector<int> >(2,2), "description");

应该管用。我还没有机会测试它,所以它可能包含一些错误。但是,至少,应该让你知道你需要什么。

于 2011-11-18T05:04:56.727 回答