C++ 推进程序选项:强制=&引用;
我使用的是C++ 推进程序选项:强制=&引用;,c++,boost,command-line,boost-program-options,C++,Boost,Command Line,Boost Program Options,我使用的是boost::program_options,这个问题仅仅是美学问题 如何强制std::string选项(或更好的all选项)仅使用带“=”的长格式 现在,我看到的是“=”被强制在我的int选项上,而字符串没有使用等号: po::options_description desc("Allowed options"); desc.add_options() (opt_help, "Show this help message") (opt_
boost::program_options
,这个问题仅仅是美学问题
如何强制std::string
选项(或更好的all选项)仅使用带“=”的长格式
现在,我看到的是“=”被强制在我的int
选项上,而字符串没有使用等号:
po::options_description desc("Allowed options");
desc.add_options()
(opt_help, "Show this help message")
(opt_int, po::value<int>()->implicit_value(10), "Set an int")
(opt_str, po::value<std::string>()->implicit_value(std::string()), "Set a string")
;
po::选项描述描述(“允许选项”);
说明添加选项()
(选择“帮助”,显示此帮助消息)
(opt_int,po::value()->隐式_值(10),“设置int”)
(opt_str,po::value()->隐式_值(std::string()),“设置字符串”)
;
上面显示的所有选项为--help
,--int=4
,--str FooBar
。我只希望选项的格式为——option=something
我试过一些款式,但没找到合适的
干杯 如果不编写自己的解析器,就无法完成这类工作
std::pair parse_选项(std::string值)
{
if(value.size()<3)
{
throw std::logic_错误(“只允许使用完整键(--key));
}
value=value.substr(2);
std::string::size\u type等号=value.find('=');
if(等号==std::string::npos)
{
如果(值=“帮助”)
{
返回std::make_pair(值,std::string());
}
抛出std::logic_错误(“仅允许键=值设置”);
}
返回std::make_pair(value.substr(0,等号),
substr(等号+1));
}
//调用解析时
po::store(po::命令行解析器(argc,argv).options(desc)。
额外的语法分析器(语法分析器选项).run(),vm);
然而,您可以用更简单的方法来实现这一点
void check_allowed(const po::parsed_options& opts)
{
const std::vector<po::option> options = opts.options;
for (std::vector<po::option>::const_iterator pos = options.begin();
pos != options.end(); ++pos)
{
if (pos->string_key != "help" &&
pos->original_tokens.front().find("=") == std::string::npos)
{
throw std::logic_error("Allowed only help and key=value options");
}
}
}
po::parsed_options opts = po::command_line_parser(argc, argv).options(desc).
style(po::command_line_style::allow_long |
po::command_line_style::long_allow_adjacent).run();
check_allowed(opts);
允许无效检查(常量po::已解析的选项和选项)
{
const std::vector options=opts.options;
for(std::vector::const_iterator pos=options.begin();
pos!=options.end();++pos)
{
如果(位置->字符串键!=“帮助”&&
pos->original_tokens.front().find(“=”==std::string::npos)
{
抛出std::logic_错误(“仅允许帮助和键=值选项”);
}
}
}
po::parsed_options opts=po::command_line_parser(argc,argv).options(desc)。
样式(po::命令行样式::允许长
po::命令行样式::长\允许\相邻)。运行();
允许检查(opts);
因此,在本例中,boost::po parse,您只需进行检查。太糟糕了,我发现“始终使用相等”样式非常简洁。谢谢
void check_allowed(const po::parsed_options& opts)
{
const std::vector<po::option> options = opts.options;
for (std::vector<po::option>::const_iterator pos = options.begin();
pos != options.end(); ++pos)
{
if (pos->string_key != "help" &&
pos->original_tokens.front().find("=") == std::string::npos)
{
throw std::logic_error("Allowed only help and key=value options");
}
}
}
po::parsed_options opts = po::command_line_parser(argc, argv).options(desc).
style(po::command_line_style::allow_long |
po::command_line_style::long_allow_adjacent).run();
check_allowed(opts);