1 #include <boost/program_options.hpp>
2
3 #include <vector>
4 #include <iostream>
5 #include <string>
6 #include <algorithm>
7 #include <iterator>
8 using std::copy;
9 using std::vector;
10 using std::string;
11 using std::cout;
12 using std::endl;
13 using std::exception;
14 using std::ostream;
15 using std::ostream_iterator;
16
17 namespace po=boost::program_options;
18
19 // output vector.
20 template <typename T>
21 ostream& operator<<(ostream& os, const vector<T>& v)
22 {
23 copy(v.begin(), v.end(), ostream_iterator<T>(os, " "));
24 return os;
25 }
26
27 int main(int argc, char*argv[])
28 {
29 try
30 {
31 po::options_description desc("general descriptions.");
32 desc.add_options()
33 ("help", "generate help information")
34 ("input-file", po::value<vector<string> >(), "input files")
35 ("link-file,l", po::value<vector<string> >(), "link file");
36
37 po::variables_map vm;
38 po::store(po::parse_command_line(argc, argv, desc), vm);
39 po::notify(vm);
40
41 if(vm.count("help"))
42 {
43 cout<<desc<<endl;
44 return 1;
45 }
46
47 if(vm.count("input-file"))
48 {
49 cout<<"Input files: "<<vm["input-file"].as<vector<string> >()
50 <<"\n";
51 }
52
53 if(vm.count("link-file"))
54 {
55 cout<<"Link file: "<<vm["link-file"].as<vector<string> >()
56 <<"\n";
57 }
58 }
59 catch(exception& e)
60 {
61 cout<<e.what()<<endl;
62 return -1;
63 }
64
65 return 0;
66 }
67
程序第20行重載了<<運算符,用于輸出vector數組.
第31行定義一個選項描述組件,然后添加允許的選項,add_options()方法返回一個特定對象,該對象重載了()運算.link-file選項指定了短名l,這樣--link-file與-l一個意思.
第37行定義一個存儲器組件對象vm.
第38行分析器parse_command_line將選項描述存儲至vm,這里用到的分析器很簡單,后面會介紹更復雜的應用.
接下來的代碼就是比對vm中存放的選項了,簡單吧,很好理解.下面是運行截圖,編譯需要添加boost program_options庫,即-lboost_program_option

對于input-file選項,每次都要輸出--input-file真的很麻煩,能不能用compiler main.cpp呢,當然可以.這種選項叫做positional option, 在第36行處加上如下代碼:
1 po::positional_options_description p;
2 p.add("input-file", -1);
3
修改第38行,我們要用到功能更強大的command_line_parse,改成如下:
1 po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
編譯運行:看下結果吧

先到這里吧,接下來再看從文件中讀選項:)

]]>