Required and Optional Arguments Using Boost Library Program Options(使用 Boost 库程序选项的必需参数和可选参数)
问题描述
我正在使用 Boost 程序选项库来解析命令行参数.
I'm using Boost Program Options Library to parse the command line arguments.
我有以下要求:
- 一旦提供了帮助",所有其他选项都是可选的;
- 如果未提供帮助",则需要所有其他选项.
我该如何处理?这是我处理这个的代码,我发现它很多余,我认为一定有一个容易做到的,对吧?
How I can deal with this? Here is the my code handling this, and I found it's very redundant, and I think there must be an easy to do, right?
推荐答案
我自己也遇到过这个问题.解决方案的关键是函数 po::store
填充 variables_map
而 po::notify
会引发遇到的任何错误,所以 vm
可以在发送任何通知之前使用.
I've run into this issue myself. The key to a solution is that the function po::store
populates the variables_map
while po::notify
raises any errors encountered, so vm
can be used prior to any notifications being sent.
因此,根据 蒂姆,根据需要将每个选项设置为必需,但在处理了帮助选项后运行 po::notify(vm)
.这样它就会退出而不会抛出任何异常.现在,将选项设置为必需,缺少选项将导致 required_option
异常被抛出并使用它的 get_option_name
方法你可以将你的错误代码减少到一个相对简单的 catch
堵塞.
So, as per Tim, set each option to required, as desired, but run po::notify(vm)
after you've dealt with the help option. This way it will exit without any exceptions thrown. Now, with the options set to required, a missing option will cause a required_option
exception to be thrown and using its get_option_name
method you can reduce your error code to a relatively simple catch
block.
作为附加说明,您的选项变量是直接通过 po::value< 设置的.-type- >( &var_name )
机制,因此您不必通过 vm["opt_name"].as< 访问它们.-type- >()
.
As an additional note, your option variables are set directly via the po::value< -type- >( &var_name )
mechanism, so you don't have to access them through vm["opt_name"].as< -type- >()
.
Peters 的回答
这篇关于使用 Boost 库程序选项的必需参数和可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!