根据文档,我可以解析风格的配置文件:

 [main section]
 string = hello world.
 [foo]
 message = Hi !

但我需要解析插件列表:
 [plugins]
 somePlugin.
 HelloWorldPlugin
 AnotherPlugin
 [settings]
 type = hello world

如何获取插件部分中的字符串 vector ?

最佳答案

对于 boost 程序选项配置文件,如果该行未声明部分,例如 [settings] ,则它需要采用 name=value 格式。对于您的示例,请将其编写如下:

[plugins]
name = somePlugin
name = HelloWorldPlugin
name = AnotherPlugin
[settings]
type = hello world

The list of plugins will now correspond to the "plugins.name" option, which needs to be a multitoken option.

Below is an example program that reads the above settings from a settings.ini file:

#include <boost/program_options.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main()
{
  namespace po = boost::program_options;

  typedef std::vector< std::string > plugin_names_t;
  plugin_names_t plugin_names;
  std::string settings_type;

  // Setup options.
  po::options_description desc("Options");
  desc.add_options()
    ("plugins.name", po::value< plugin_names_t >( &plugin_names )->multitoken(),
                     "plugin names" )
    ("settings.type", po::value< std::string >( &settings_type ),
                      "settings_type" );

  // Load setting file.
  po::variables_map vm;
  std::ifstream settings_file( "settings.ini" , std::ifstream::in );
  po::store( po::parse_config_file( settings_file , desc ), vm );
  settings_file.close();
  po::notify( vm );

  // Print settings.
  typedef std::vector< std::string >::iterator iterator;
  for ( plugin_names_t::iterator iterator = plugin_names.begin(),
                                      end = plugin_names.end();
        iterator < end;
        ++iterator )
  {
    std::cout << "plugin.name: " << *iterator << std::endl;
  }
  std::cout << "settings.type: " << settings_type << std::endl;

  return 0;
}

产生以下输出:

plugin.name: somePlugin
plugin.name: HelloWorldPlugin
plugin.name: 另一个插件
settings.type: Hello World

关于c++ - Boost 程序选项 - 获取部分中的所有条目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11065938/

10-09 08:21
查看更多