• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
6 /** This example shows how to support custom options syntax.
7 
8     It's possible to install 'custom_parser'. It will be invoked on all command
9     line tokens and can return name/value pair, or nothing. If it returns
10     nothing, usual processing will be done.
11 */
12 
13 
14 #include <boost/program_options/options_description.hpp>
15 #include <boost/program_options/parsers.hpp>
16 #include <boost/program_options/variables_map.hpp>
17 
18 using namespace boost::program_options;
19 
20 #include <iostream>
21 using namespace std;
22 
23 /*  This custom option parse function recognize gcc-style
24     option "-fbar" / "-fno-bar".
25 */
reg_foo(const string & s)26 pair<string, string> reg_foo(const string& s)
27 {
28     if (s.find("-f") == 0) {
29         if (s.substr(2, 3) == "no-")
30             return make_pair(s.substr(5), string("false"));
31         else
32             return make_pair(s.substr(2), string("true"));
33     } else {
34         return make_pair(string(), string());
35     }
36 }
37 
main(int ac,char * av[])38 int main(int ac, char* av[])
39 {
40     try {
41         options_description desc("Allowed options");
42         desc.add_options()
43         ("help", "produce a help message")
44         ("foo", value<string>(), "just an option")
45         ;
46 
47         variables_map vm;
48         store(command_line_parser(ac, av).options(desc).extra_parser(reg_foo)
49               .run(), vm);
50 
51         if (vm.count("help")) {
52             cout << desc;
53             cout << "\nIn addition -ffoo and -fno-foo syntax are recognized.\n";
54         }
55         if (vm.count("foo")) {
56             cout << "foo value with the value of "
57                  << vm["foo"].as<string>() << "\n";
58         }
59     }
60     catch(exception& e) {
61         cout << e.what() << "\n";
62     }
63 }
64