我正在使用 boost::program_options 从配置文件中获取参数。
我知道我可以手动创建一个文件,程序选项会解析它。但我正在寻找一种让程序自动生成文件的方法。意思是打印出选项的名称和它的值。例如:
>./main
没有选项会生成如下所示的 init.cfg
[wave packet]
width = 1
position = 2.0
[calculation parameters]
levels = 15
然后我会进入该文件使用文本编辑器更改值并使用此文件:
>./main init.cfg
解决这个问题的一个好方法是让 variables_map 拥有operator<<
. 这样我就可以将它写入文件。更改值。读取文件。都采用相同的格式,无需编写每一行。
我在文档或示例中找不到类似的东西。请让我知道这是否可能
编辑:Sam Miller 展示了如何分段解析 ini 文件。但是,我仍然无法从 boost::program_options::variables_map vm 获取值。我尝试了以下
for(po::variables_map::iterator it = vm.begin(); it != vm.end(); ++it)
{
if(it->first!="help"&&it->first!="config")
cout << "first - " << it->first << ", second - " << it->second.value() << "\n";
}
而不是it->second.value()
,出现错误。我也试过了it->second
。我也有一个错误:
icpc -lboost_serialization -lboost_program_options -c programOptions.cc
programOptions.cc(60): error: no operator "<<" matches these operands
operand types are: std::basic_ostream<char, std::char_traits<char>> << boost::any
cout << "first - " << it->first << ", second - " << it->second.value() << "\n";
^
compilation aborted for programOptions.cc (code 2)
make: *** [programOptions.o] Error 2
如果我使用it->second.as<int>()
但不是所有值都是整数,我会正确获得值,一旦我达到双倍,程序就会崩溃:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_any_cast> >'
what(): boost::bad_any_cast: failed conversion using boost::any_cast