Vector arguments in Boost Program Options

Szabolcs picture Szabolcs · Nov 18, 2011 · Viewed 26.8k times · Source

I have two related questions:

  1. What is the simplest way to allow passing a series of values, using Boost Program Options? My aim is to avoid prog --opt 1 --opt 2 --opt 3 and have prog --opt 1 2 3 instead.

  2. What is the simplest way to have an option that takes exactly two numbers, e.g. prog --opt 137 42?

(I don't need any "free" program parameters.)

Answer

Bee picture Bee · Dec 31, 2012

This is a late answer but I hope it helps someone. You could easily use the same technique in item #1, except you need to add another validation on the number of items in your vector:

from rcollyer's example:

namespace po = boost::program_options;
po::option_descriptions desc("");

desc.add_options()
 ("opt", po::value<std::vector<int> >()->multitoken(), "description");

po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm); 

vector<int> opts;
if (!vm["opt"].empty() && (opts = vm["opt"].as<vector<int> >()).size() == 2) {
  // good to go
}