custom_syntax.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright Vladimir Prus 2002-2004.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt
  4. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. /** This example shows how to support custom options syntax.
  6. It's possible to install 'custom_parser'. It will be invoked on all command
  7. line tokens and can return name/value pair, or nothing. If it returns
  8. nothing, usual processing will be done.
  9. */
  10. #include <boost/program_options/options_description.hpp>
  11. #include <boost/program_options/parsers.hpp>
  12. #include <boost/program_options/variables_map.hpp>
  13. using namespace boost::program_options;
  14. #include <iostream>
  15. using namespace std;
  16. /* This custom option parse function recognize gcc-style
  17. option "-fbar" / "-fno-bar".
  18. */
  19. pair<string, string> reg_foo(const string& s)
  20. {
  21. if (s.find("-f") == 0) {
  22. if (s.substr(2, 3) == "no-")
  23. return make_pair(s.substr(5), string("false"));
  24. else
  25. return make_pair(s.substr(2), string("true"));
  26. } else {
  27. return make_pair(string(), string());
  28. }
  29. }
  30. int main(int ac, char* av[])
  31. {
  32. try {
  33. options_description desc("Allowed options");
  34. desc.add_options()
  35. ("help", "produce a help message")
  36. ("foo", value<string>(), "just an option")
  37. ;
  38. variables_map vm;
  39. store(command_line_parser(ac, av).options(desc).extra_parser(reg_foo)
  40. .run(), vm);
  41. if (vm.count("help")) {
  42. cout << desc;
  43. cout << "\nIn addition -ffoo and -fno-foo syntax are recognized.\n";
  44. }
  45. if (vm.count("foo")) {
  46. cout << "foo value with the value of "
  47. << vm["foo"].as<string>() << "\n";
  48. }
  49. }
  50. catch(exception& e) {
  51. cout << e.what() << "\n";
  52. }
  53. }