Boost.Program_options fixed number of tokens

boost-program-options, c++

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 methods `min_tokens` and `max_tokens`, which seems to do exactly what you want. If you look at the definition of class `typed_value` ( this is the object that gets created, when you call `po::value< std::vector<int> >(&nums)->multitoken()`) you can get the grasp of how the methods should be overridden.

Problem

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?

Original source