开发者

Parameters with and without arguments in boost::program_options

I wrote a small app that uses boost::program_options for command-line parsing. I'd like to have some options that set a value if the argument is present, and alternately pr开发者_如何学JAVAints the current value if the parameter is given but no argument is present. So "set-mode" would look like:

dc-ctl --brightness 15

and "get mode" would be:

dc-ctl --brightness
brightness=15

The problem is, I don't know how to handle the second case without catching this exception:

error: required parameter is missing in 'brightness'

Is there an easy way to avoid having it throw that error? It happens as soon as the arguments are parsed.


I got a partial solution from How to accept empty value in boost::program_options which suggests using the implicit_value method on those parameters that may or may not have arguments present. So my call to initialize the "brightness" parameter looks like this:

 ("brightness,b", po::value<string>()->implicit_value(""),

I then iterate over the variable map and for any argument that's a string, I check if it's empty and if so I print the current value. That code looks like this:

    // 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;
    }

UPDATE: this changes the aforementioned syntax, when using implicit values, now arguments, when given, must be of the form:

./dc-ctl -b500

instead of

./dc-ctl -b 500

Hope this is helpful to someone else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜