boost :: program_options中带和不带参数的参数

tma*_*tth 7 c++ command-line-arguments boost-program-options

我写了一个小应用程序,它使用boost :: program_options进行命令行解析.如果参数存在,我想有一些设置值的选项,如果给出参数但是没有参数,则交替打印当前值.所以"设置模式"看起来像:

dc-ctl --brightness 15
Run Code Online (Sandbox Code Playgroud)

和"获取模式"将是:

dc-ctl --brightness
brightness=15
Run Code Online (Sandbox Code Playgroud)

问题是,我不知道如何处理第二种情况而不捕获此异常:

error: required parameter is missing in 'brightness'
Run Code Online (Sandbox Code Playgroud)

是否有一种简单的方法可以避免它抛出该错误?一旦解析了参数,就会发生这种情况.

tma*_*tth 4

我从如何接受 boost::program_options 中的空值中得到了部分解决方案,它建议对那些可能存在或不存在参数的参数使用隐式值方法。所以我对初始化“亮度”参数的调用如下所示:

 ("brightness,b", po::value<string>()->implicit_value(""),
Run Code Online (Sandbox Code Playgroud)

然后,我迭代变量映射,对于任何字符串参数,我检查它是否为空,如果是,则打印当前值。该代码如下所示:

    // check if we're just printing a feature's current value
    bool gotFeature = false;
    for (po::variables_map::iterator iter = vm.begin(); iter != vm.end(); ++iter)
    {
        /// parameter has been given with no value
        if (iter->second.value().type() == typeid(string))
            if (iter->second.as<string>().empty())
            {
                gotFeature = true;
                printFeatureValue(iter->first, camera);
            }
    }

    // this is all we're supposed to do, time to exit
    if (gotFeature)
    {
        cleanup(dc1394, camera, cameras);
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

更新:这改变了上述语法,当使用隐式值时,现在参数在给出时必须采用以下形式:

./dc-ctl -b500
Run Code Online (Sandbox Code Playgroud)

代替

./dc-ctl -b 500
Run Code Online (Sandbox Code Playgroud)

希望这对其他人有帮助。