具有多个令牌的boost :: program_options配置文件选项 [英] boost::program_options config file option with multiple tokens

查看:342
本文介绍了具有多个令牌的boost :: program_options配置文件选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法像从命令行中一样从配置文件多令牌选项中读取内容.配置文件的语法是什么?

I can not seem to be able to read from config file multitoken options like I can from command line. What is the syntax for the config file?

这是添加选项说明的方式:

This is how the option description is added:

//parser.cpp
- - -
po::options_description* generic;
generic=new po::options_description("Generic options");
generic->add_options()
("coordinate",po::value<std::vector<double> >()->multitoken(),"Coordinates (x,y)");

之后,我解析命令和配置文件.

After which I parse command and config-files.

在命令行-坐标1 2"上工作.但是,当我尝试使用配置文件时:

On command line '--coordinate 1 2' works. However, when I try in config file:

coordinate = 1,2

coordinate= 1 2

它无法给出invalid_option_value异常.那么在使用多令牌选项的情况下,配置文件的语法到底是什么?

It fails giving a invalid_option_value exception. So what exactly is the syntax for config files in case of multitoken options?

推荐答案

您可以通过编写自定义验证程序来实现所需的行为.此自定义验证器接受:

You can achieve the behavior you seek by writing a custom validator. This custom validator accepts :

./progname --coordinate 1 2
./progname --coordinate "1 2"
#In config file:
coordinate= 1 2

这是代码:

struct coordinate {
  double x,y;
};

void validate(boost::any& v,
  const vector<string>& values,
  coordinate*, int) {
  coordinate c;
  vector<double> dvalues;
  for(vector<string>::const_iterator it = values.begin();
    it != values.end();
    ++it) {
    stringstream ss(*it);
    copy(istream_iterator<double>(ss), istream_iterator<double>(),
      back_inserter(dvalues));
    if(!ss.eof()) {
      throw po::validation_error("Invalid coordinate specification");
    }
  }
  if(dvalues.size() != 2) {
    throw po::validation_error("Invalid coordinate specification");
  }
  c.x = dvalues[0];
  c.y = dvalues[1];
  v = c;
}
...
    po::options_description config("Configuration");
    config.add_options()
        ("coordinate",po::value<coordinate>()->multitoken(),"Coordinates (x,y)")
        ;

参考文献:

  • http://www.boost.org/doc/libs/1_46_1/doc/html/program_options/howto.html#id2219998
  • https://stackoverflow.com/tags/boost-program-options/hot
  • Handle complex options with Boost's program_options

这篇关于具有多个令牌的boost :: program_options配置文件选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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