Search code examples
c++command-lineboostboost-program-options

Accepting negative doubles with boost::program_options


I need to be able to have boost::program_options parse an array of doubles that are passed on a command line. For positive doubles, this is no problem, of course (use multitoken with std::vector<double> in add_options), but for negative ones, I know that these are ambiguous arguments.

Here is a demonstration of what I would like to take in:

mycommand --extent -1.0 -2.0 -3.0 1.0 2.0 3.0 --some-other-argument somevalue

extent is to be backed by a Bounds class with at least one constructor that takes in six individual T arguments (in this case -- double).

template <typename T>
class Bounds
{
public:
    typedef T value_type;
    typedef typename std::vector< Range<T> >::size_type size_type;

    typedef typename std::vector< Range<T> > Ranges;

    Bounds( T minx, T miny, T minz, 
            T maxx, T maxy, T maxz)
    {
        // fill Ranges vector
    }

private:
    Ranges ranges;
};

What else must I supply to support using add_options take in the Bounds class? I'd like to do something similar to this. Possible?

namespace po = boost::program_options;
po::options_description options("options");

options.add_options()
    ("extent,e", po::value< Bounds< double > >(), "Extent to clip points to")

po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
  options(options).positional(p).run(), vm);

po::notify(vm);

if (vm.count("extent")) 
{
    Bounds<double> bounds = vm["extent"].as< Bounds<double> >();
    // do other stuff
}

Solution

  • The approach to handling negative numbers specified here might also work for you.

    I was parsing it by the simple parser

    store(command_line_parser(argc, argv).options(commands).run(), vm);
    

    , but solution was to use the extended one:

    parse_command_line