Boost.Program_options provides a facility to pass multiple tokens via command line arguments as follows:
std::vector<int> nums;
po::options_description desc("Allowed options");
desc.add_options()
("help", "Produce help message.")
("nums", po::value< std::vector<int> >(&nums)->multitoken(), "Numbers.")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
However, what is the preferred way of accepting only a fixed number of arguments? The only solution I could come is to manually assign values:
int nums[2];
po::options_description desc("Allowed options");
desc.add_options()
("help", "Produce help message.")
("nums", "Numbers.")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("nums")) {
// Assign nums
}
This feels a bit clumsy. Is there a better solution?
The boost library only provides the predefined mechanisms. A quick search didn’t find something with a fixed number of values. But you can create this yourself. The
po::value< std::vector<int> >(&nums)->multitoken()is just a specialized value_semantic class. As you can see, this class offers the methodsmin_tokensandmax_tokens, which seems to do exactly what you want. If you look at the definition of classtyped_value( this is the object that gets created, when you callpo::value< std::vector<int> >(&nums)->multitoken()) you can get the grasp of how the methods should be overridden.