【发布时间】:2015-06-29 13:55:54
【问题描述】:
我正在使用 program_options 来解析 commandLine 和配置选项,我发现似乎是一个错误。使用具有相似名称的矢量选项时会出现问题。如果我有一个 unspecified 参数“myParam”和另一个 specified 参数“myParam2”,则库会将 myParam 的值附加到 myParam2。
例如,当我这样调用我的程序时:
./model -myParam2={7,8,9} -myParam={5,6}
我明白了:
myParam not declared <-- This is OK
myParam2 size: 5 <-- I would expect this to be size:3
我将代码简化为以下显示问题的示例:
// Declare a group of options that will be allowed both on command line and in config file
po::options_description options("Simulator Configuration (and Command Line) options");
options.add_options()
//("myParam", po::value<std::vector<int>>(), "test") --> If I uncomment this line, it works as expected
("myParam2", po::value<std::vector<int>>(), "test");
// parse the cmdline options
auto parsed_cmdLine_options = po::command_line_parser(ac,av).options(options)
.style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise) // to enable options to start with a '-' instead of '--'
.allow_unregistered() // to allow generic parameters (which can be read by models)
.run();
po::store(parsed_cmdLine_options, simulatorParams);
notify(simulatorParams);
// print parsed options
std::vector<int> tmp1, tmp2;
if(simulatorParams.count("myParam")){
tmp1 = simulatorParams["myParam"].as<std::vector<int>>();
std::cout << "myParam size: " << tmp1.size() << "\n";
if(tmp1.size()!= 2){
throw "Wrong Size";
}
}else
{
std::cout << "myParam not declared \n";
}
if(simulatorParams.count("myParam2")){
tmp2 = simulatorParams["myParam2"].as<std::vector<int>>();
std::cout << "myParam2 size: " << tmp2.size() << "\n";
if(tmp2.size()!= 3){
throw "Wrong Size";
}
}
如果我取消注释注册“myParam”的行,它会按预期工作:
options.add_options()
("myParam", po::value<std::vector<int>>(), "test")
("myParam2", po::value<std::vector<int>>(), "test");
打印出来:
myParam size: 2
myParam2 size: 3
我真的需要使用未注册的选项,因为我稍后会在执行过程中重新处理它们。
这似乎是一个非常简单的错误,所以也许我在使用该库时出现了某种错误。
之前有没有人看到过这个问题,或者有任何解决方法的想法?
非常感谢!
编辑: 我正在使用提升 1.48。 我为参数尝试了其他几种语法,它的行为方式相同:
- 带有双“--”:./model --myParam2={7,8,9} --myParam={5,6}
- 每个声明使用单个值:./model --myParam2=7 --myParam2=8 --myParam2=9 --myParam=5 --myParam=6
- 结合前一个。
【问题讨论】:
-
Boost 1.48 现在开始有点老了,你试过用更高版本吗?
标签: c++ boost boost-program-options