解析Boost program_options中配置文件的未注册选项? [英] Parsing unregistered options for config files in Boost program_options?
问题描述
使用命令行选项,我可以执行以下操作:
With command line options, I can do the following:
po::variables_map vm;
auto parsedOptions = po::command_line_parser(argc, argv).options(optionsDescription1).allow_unregistered().run();
po::store(parsedOptions, vm);
po::notify(vm);
auto unregistered = po::collect_unrecognized(parsedOptions.options, po::include_positional);
po::variables_map vm2;
auto parsedOptions2 = po::command_line_parser(unregistered).options(optionsDescription2).run();
po::store(parsedOptions2, vm2);
po::notify(vm2);
这很好用,因为collect_unregistered()
收集的命令行标记与在命令行中显示的完全相同.但是,它不适用于配置文件.我可以解析一个允许未注册选项的配置文件,但是当我收集未注册选项时,会得到无法使用的结果.
This works fine, because collect_unregistered()
collects the command line tokens exactly as it appeared in the command line. However, it doesn't work for config files. I can parse a config file allowing unregistered options, but when I collect the unregistered options, I get a result that I cannot use.
po::variables_map vm;
auto parsedOptions = po::parse_config_file<char>(filename, optionsDescription1, true);
po::store(parsedOptions, vm);
po::notify(vm);
auto unregistered = po::collect_unrecognized(parsedOptions.options, po::include_positional);
在这种情况下,我得到列出的选项的名称和值.例如,如果配置文件包含以下选项:
In this case I get the names and values of the options listed. For example, if the config file contained the following options:
unregistered_option1=value1
unregistered_option2=value2
然后我在字符串向量unregistered
中获得值unregistered_option1
,value1
,unregistered_option2
,value2
. Boost的解析器无法对此格式做任何有用的事情.有什么方法可以解析此列表(即使用不同的options_description
解析第一个options_description
无法识别的所有选项)?当然,我可以使用设置了allow_unregistered
的第二个options_description
再次解析该文件,但是然后我无法检查两个描述都不知道的选项.
Then I get the values unregistered_option1
, value1
, unregistered_option2
, value2
in the string vector unregistered
. Boost's parser cannot do anything useful with this format. Is there any way to parse this list (i.e. parse all the options that were unrecognized by the first options_description
with a different options_description
)? Of course I can just parse the file again with the second options_description
with allow_unregistered
set, but then I can't check for options unknown to both descriptions.
推荐答案
您不必依赖collect_unrecognized()
返回值的不完善之处,因此,您始终可以自己检测,处理和重构选项. parse_config_file()
保持与未知选项的观察关系:
You don't have to rely on the imperfections of collect_unrecognized()
return value, you can always detect, handle and reconstruct the options yourself, as the result of parse_config_file()
keeps the observed relationship for the unknown options:
auto parsed_options = parse_config_file(ifs, config_file_options, true);
store(parsed_options, vm);
...
for (const auto& o : parsed_options.options) {
if (vm.find(o.string_key) == vm.end()) {
// an unknown option
cout << o.string_key << "=" << o.value << "\n";
}
}
这篇关于解析Boost program_options中配置文件的未注册选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!