Parameters with and without arguments in boost :: program_options

I wrote a small application that uses boost :: program_options to parse the command line. I would like to have some parameters that set the value if the argument is present, and prints the current value alternately if the parameter is specified, but the argument is missing. So, "set-mode" will look like this:

dc-ctl --brightness 15 

and "get mode" will be:

 dc-ctl --brightness brightness=15 

The problem is that 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 this error? This happens as soon as the arguments are parsed.

+7
c ++ command-line-arguments boost-program-options
source share
1 answer

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

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

Then I iterate over the map variable and for any argument that the line is, I check if it is empty, and if so, I print the current value. This code is as follows:

  // check if we're just printing a feature 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 when given the arguments should look like:

 ./dc-ctl -b500 

instead

 ./dc-ctl -b 500 

Hope this helps someone else.

+4
source share

All Articles