boost program_options

一直认为boost都是hpp直接调用就可以了,最近遇到两个例子都不是这样的一个是boost的thread,另外一个就是这个了,boost在编译好之后会有库文件的,注意不是在当前的libs下面,而是stage/libs下面,我们在使用这个模块的时候要加上相应的动态或者静态的库。

当我们写一些小程序的时候难免要写一些输入参数,当然用linux自带的也可以

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. int next_option;  
  2. /* Parse options. */  
  3. do {  
  4.     next_option = getopt_long (argc, argv, short_options, long_options, NULL);  
  5. }while(next_options);  

但是我们要写很多error handing,user manual 之类的, 比较麻烦,而且打印出来的格式也不是很好看。

那boost的program_options可以帮助我们解决这个问题。

 

boost program_options不仅支持配置command line,而且支持配置像INI一样的配置文件,这个模块非常好,下面是对配置文件格式的说明:

语法大致有三条,一个是name value的对应关系,另一个是section的模块,最后一个是注释的规范。

Configuration file parser

The parse_config_file function implements parsing of simple INI-like configuration files. Configuration file syntax is line based:

  • A line in the form:

    name=value
            

    gives a value to an option.

  • A line in the form:

    [section name]
            

    introduces a new section in the configuration file.

  • The # character introduces a comment that spans until the end of the line.

The option names are relative to the section names, so the following configuration file part:

[gui.accessibility]
visual_bell=yes
      

is equivalent to

gui.accessibility.visual_bell=yes
      

如何实现一对多的支持?

如果只是command line里面的很简单 只要加一个token就可以,但是如果是配置文件的则validate

实现很简单:

po::value<vector<float> >(&(paralist))->multitoken()

注意利用第三个参数重载

namespace boost{
void validate(boost::any& v,
          const vector<string>& values,
            vector<float>*, int) {
    cout << "hello" << endl;
        vector<double> dvalues;
          for(vector<string>::const_iterator it = values.begin();
                      it != values.end();
                          ++it) {
                  //stringstream ss(*it);
                  cout<<*it<<endl;
                            }
}
}

如何支持负数?

负数和program option会有冲突,一般通过加引号来处理,或者通过去除短option,只支持长option

char* v[] = {"name","--IDlist=0","1","200","-2"};
int c = 5;

std::vector<int> IDlist;

namespace po = boost::program_options;     
po::options_description commands("Allowed options");
commands.add_options()              
    ("IDlist",po::value< std::vector<int> >(&IDlist)->multitoken(), "Which IDs to trace: ex. --IDlist=0 1 200 -2")
    ("help","print help")
;

po::variables_map vm;
po::store(parse_command_line(c, v, commands, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);
po::notify(vm);

BOOST_FOREACH(int id, IDlist)
    std::cout << id << std::endl;



下面讲一下具体的使用体会

1 打印很方便尤其是help manual, 对各种命令的错误的提示很好

2 type 和 name直接关联,根据名字直接读到变量中

3 支持command和文本配置文件,不同的源之间可以合并使用

4 没有办法指定变量的有效范围。

总之,用了之后颇有点专业软件的风范。

http://www.boost.org/doc/libs/1_45_0/doc/html/program_options.html

http://stackoverflow.com/questions/2935587/handle-complex-options-with-boosts-program-options/2939249#2939249

原文地址:https://www.cnblogs.com/lidabo/p/3953303.html