rub*_*nvb 5 c++ boost boost-program-options
我正在使用Boost.program_options来解析我实现POSIX实用程序的命令行.举个简单的例子吧cmp.
现在我想有一个额外的参数--help来显示所有参数的描述,这在这种情况下很重要.我有:
po::options_description options("Options");
options.add_options()("help", "Show this help output.")
(",l", "(Lowercase ell.) Write the byte number (decimal) and the differing bytes (octal) for each difference.")
(",s", "Write nothing for differing files; return exit status only.")
po::positional_options_description operands;
operands.add("file1", 1);//, "A pathname of the first file to be compared. If file1 is '-', the standard input shall be used.")
operands.add("file2", 1);//, "A pathname of the second file to be compared. If file2 is '-', the standard input shall be used.");
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(options).positional(operands).run(), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << "cmp: compare two files\nUsage: cmp [ -l | -s ] file1 file2\n" << options;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是无法显示file1和file2选项的说明.我当然可以添加它们options,但这会添加至少两个不需要的参数[-]-file{1,2},我真的不想要.我只想要这个输出--help(没有显然硬编码):
cmp: compare two files
Usage: cmp [ -l | -s ] file1 file2
Options:
--help Show this help output.
-l (Lowercase ell.) Write the byte number (decimal) and the differing bytes (octal) for each difference.
-s Write nothing for differing files; return exit status only.
Operands:
file1 A pathname of the first file to be compared. If file1 is '-', the standard input shall be used.
file2 A pathname of the second file to be compared. If file2 is '-', the standard input shall be used.
Run Code Online (Sandbox Code Playgroud)
有没有办法在不乱砍图书馆的情况下实现这一目标?我认为这是非常基本的东西,但我在任何教程中都找不到它.
更新为了每个人的利益,我提交了一个功能请求,以一种有希望向后兼容的方式.
这并不理想,但是如何创建一组“虚拟”程序选项,让 boost::program_options 格式化程序为您格式化其帮助文本,然后通过快速替换删除破折号?
然后除了帮助文本之外还输出该帮助options文本。
像这样的东西:
po::options_description dummy_options("Operands");
dummy_options.add_options()
("file1", po::value<std::string>(), "A pathname of the first file to be compared. If file1 is '-', the standard input shall be used.")
("file2", po::value<std::string>(), "A pathname of the second file to be compared. If file2 is '-', the standard input shall be used.")
;
std::stringstream s;
s << dummy_options;
std::string dummy_help_text = s.str();
boost::replace_all(dummy_help_text, "--", "");
boost::replace_all(dummy_help_text, "arg", " ");
std::cout << dummy_help_text << std::endl;
Run Code Online (Sandbox Code Playgroud)
输出如下所示:
Operands:
file1 A pathname of the first file to be compared. If file1
is '-', the standard input shall be used.
file2 A pathname of the second file to be compared. If file2
is '-', the standard input shall be used.
Run Code Online (Sandbox Code Playgroud)
这并不理想,因为除其他外,列之间的间距与其他options输出的帮助输出不匹配。但对于一些快速而肮脏的、基本上有效的东西来说,这可能没问题。
无论如何,这是一个想法。
(我在 Boost.Program_Options API 中也没有看到任何允许您以“正确”方式执行此操作的内容。https: //stackoverflow.com/a/3621947/368896给出了不支持此类操作的提示,但现在已经 3 岁了。)
| 归档时间: |
|
| 查看次数: |
232 次 |
| 最近记录: |