gpt4 book ai didi

c++ - 带有可选参数的 Poco 选项

转载 作者:行者123 更新时间:2023-12-04 15:04:26 25 4
gpt4 key购买 nike

我有一个基于 Poco (v1.9.4) 的类

class PreprocessingApp : public Poco::Util::Application

使用这两种方法:

void PreprocessingApp::defineOptions(OptionSet& options)
{
Application::defineOptions(options);

options.addOption(
Option("proxy", "p", "Proxify connection")
.required(false)
.repeatable(false)
.argument("the value", false)
.callback(OptionCallback<PreprocessingApp>(this, &PreprocessingApp::handleBooleanOption))
);

options.addOption(
Option("test", "t", "Test something")
.required(true)
.repeatable(false)
.callback(OptionCallback<PreprocessingApp>(this, &PreprocessingApp::handleBooleanOption))
);
}

void PreprocessingApp::handleBooleanOption(const string& name, const string& value)
{
bool actualValue = value.empty() | value == "true" | value == "1";
config().setBool(name, actualValue);
}

如您所见,“代理”是一个 bool 选项。我添加了 ".argument("the value", false)"以允许使用此选项传递参数,但将 "required"标记为 false 以使其成为可选的。
这样我希望允许这个功能:

PreprocessingApp [-p [value]] -t [value]

两种变体都应该有效:

PreprocessingApp -p -t 
PreprocessingApp -p true -t

实际调试handleBooleanOption时,“value”始终为空“”。
需要切换为true(.argument("the value", true))时,"value"为"-t",省略下一个选项处理。

是否有任何解决方案可以使其按预期工作?

最佳答案

根据 Poco documentation :

Option arguments can be specified in three ways. If a Unix shortoption ("-o") is given, the argument directly follows the option name,without any delimiting character or space ("-ovalue"). In defaultoption mode, or if a Unix long option ("--option") is given, theoption argument is delimited from the option name with either an equalsign ('=') or a colon (':'), as in "--option=value" or"/option:value". Finally, a required option argument can be specifiedon the command line after the option, delimited with a space, as in"--option value" or "-o value". The latter only works for requiredoption arguments, not optional ones.

基本上,必需参数需要在名称和值之间有一个空格,而可选参数则不需要。因此,对于您的可选参数,请像这样指定它:-ptrue--proxytrue--proxy:true

对于必需的参数,这里还有一个问题。您可能认为将 setter .required(true)Poco::Util::Option 一起使用就足以在代码中定义必需的参数,但显然不是.您还必须使用 setter .argument(),它默认将 required 设置为 true:

Option & argument(
const std::string & name,
bool required = true
);

因此将所需参数的代码更改为:

options.addOption(
Poco::Util::Option("test", "t", "Test something")
.required(true)
.repeatable(false)
.argument("test")
.callback(Poco::Util::OptionCallback<ModbusInterface>(this, &ModbusInterface::handleBooleanOption))
);

然后你应该可以像这样调用你的应用程序,例如:

PreprocessingApp -ptrue -t true

关于c++ - 带有可选参数的 Poco 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66423495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com