Boost 程序选项允许输入值集
有没有办法为参数设置允许的输入变量集?例如,参数“arg”只能具有“cat”和“dog”等字符串值。
Is there a way to set an allowed set of input variables for parameters? For example parameter "arg" can have only string values like "cat" and "dog".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用自定义验证器 功能。为您的选项定义一个不同的类型,然后重载该类型的
validate
函数。该代码引发的异常与任何其他无效选项值引发的异常没有什么不同,因此您应该已经准备好处理它们。
定义选项时,使用特殊选项类型,而不仅仅是
string
:我编写了一个 live演示如何使用此代码的示例。
You can use the custom validator feature. Define a distinct type for your option, and then overload the
validate
function on that type.The exceptions thrown from that code are no different from the exceptions thrown for any other invalid option value, so you should already be prepared to handle them.
Use the special option type instead of just
string
when you define your options:I've composed a live example demonstrating use of this code.
一个非常简单的方法是将“animal”作为普通字符串,然后在通知后进行测试并在需要时抛出。
A very simple approach is to have "animal" as a normal string and after notify you test and throw if needed.
我浏览了 Boost.Program_options 文档,对我来说,你是否可以做到这一点并不明显。我的印象是该库主要关注解析命令行,而不是验证它。您也许可以使用 自定义来解决问题验证器,但这涉及到当你得到错误的输入时抛出异常(这可能是比你想要的更严重的错误)。我认为该功能更适合确保您确实获得了一个字符串,而不是“猫”或“狗”。
我能想到的最简单的解决方案是让库正常解析命令行,然后添加您自己的代码以验证
--arg
是否设置为cat
或狗
。然后,您可以打印错误并退出,恢复到一些合适的默认值,或者您喜欢的任何内容。I've skimmed through the Boost.Program_options documentation, and it's not at all obvious to me whether you can do that. I get the impression that the library is primarily concerned with parsing the command line, not validating it. You might be able to work something up with a custom validator, but that involves throwing exceptions when you get bad inputs (which may be a more severe error than you want). I think that feature is more geared towards making sure you actually got a string, not that it was "cat" or "dog."
The simplest solution I can think of is to let the library parse the command-line as normal, then add your own code later to verify
--arg
was set tocat
ordog
. You can then print an error and exit, revert to some suitable default, or whatever you like.