options_description.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #include <boost/program_options.hpp>
  6. using namespace boost;
  7. namespace po = boost::program_options;
  8. #include <iostream>
  9. #include <algorithm>
  10. #include <iterator>
  11. using namespace std;
  12. // A helper function to simplify the main part.
  13. template<class T>
  14. ostream& operator<<(ostream& os, const vector<T>& v)
  15. {
  16. copy(v.begin(), v.end(), ostream_iterator<T>(os, " "));
  17. return os;
  18. }
  19. int main(int ac, char* av[])
  20. {
  21. try {
  22. int opt;
  23. int portnum;
  24. po::options_description desc("Allowed options");
  25. desc.add_options()
  26. ("help", "produce help message")
  27. ("optimization", po::value<int>(&opt)->default_value(10),
  28. "optimization level")
  29. ("verbose,v", po::value<int>()->implicit_value(1),
  30. "enable verbosity (optionally specify level)")
  31. ("listen,l", po::value<int>(&portnum)->implicit_value(1001)
  32. ->default_value(0,"no"),
  33. "listen on a port.")
  34. ("include-path,I", po::value< vector<string> >(),
  35. "include path")
  36. ("input-file", po::value< vector<string> >(), "input file")
  37. ;
  38. po::positional_options_description p;
  39. p.add("input-file", -1);
  40. po::variables_map vm;
  41. po::store(po::command_line_parser(ac, av).
  42. options(desc).positional(p).run(), vm);
  43. po::notify(vm);
  44. if (vm.count("help")) {
  45. cout << "Usage: options_description [options]\n";
  46. cout << desc;
  47. return 0;
  48. }
  49. if (vm.count("include-path"))
  50. {
  51. cout << "Include paths are: "
  52. << vm["include-path"].as< vector<string> >() << "\n";
  53. }
  54. if (vm.count("input-file"))
  55. {
  56. cout << "Input files are: "
  57. << vm["input-file"].as< vector<string> >() << "\n";
  58. }
  59. if (vm.count("verbose")) {
  60. cout << "Verbosity enabled. Level is " << vm["verbose"].as<int>()
  61. << "\n";
  62. }
  63. cout << "Optimization level is " << opt << "\n";
  64. cout << "Listen port is " << portnum << "\n";
  65. }
  66. catch(std::exception& e)
  67. {
  68. cout << e.what() << "\n";
  69. return 1;
  70. }
  71. return 0;
  72. }