Boost.Program_options fixed number of tokens

Boost.Program_options provides the ability to skip multiple tokens using 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 to accept only a fixed number of arguments? The only solution I could find was 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 is a little awkward. Is there a better solution?

+4
source share
1 answer

The acceleration library provides only predefined mechanisms. A quick search did not find something with a fixed number of values. But you can create it yourself. po::value< std::vector<int> >(&nums)->multitoken() is only the specialized class value_semantic . As you can see, this class offers the min_tokens and max_tokens , which seem to do exactly what you want. If you look at the definition of the typed_value class (this is an object that is created when you call po::value< std::vector<int> >(&nums)->multitoken() ), you can get an understanding of how methods should be overridden .

+2
source

Source: https://habr.com/ru/post/1303287/


All Articles