Posted on 2010-07-05 23:08
浩毛 閱讀(1795)
評論(2) 編輯 收藏 引用 所屬分類:
C & C++
boost里的program_options提供程序員一種方便的命令行和配置文件進行程序選項設置的方法。
其文檔例子中有如下代碼:
1 using namespace boost::program_options;
2 //聲明需要的選項
3 options_description desc("Allowed options");
4 desc.add_options()
5 ("help,h", "produce help message")
6 ("person,p", value<string>()->default_value("world"), "who");
看第4到6行,是不是感覺很怪?這種方式體現了函數式編程中最大的特點:函數是一類值,引用資料來說,
所謂“函數是一類值(First Class Value)”指的是函數和值是同等的概念,一個函數可以作為另外一個函數的參數,也可以作為值使用。如果函數可以作為一類值使用,那么我們就可以寫出一些函數,使得這些函數接受其它函數作為參數并返回另外一個函數。比如定義了f和g兩個函數,用compose(f,g)的風格就可以生成另外一個函數,使得這個函數執行f(g(x))的操作,則可稱compose為高階函數(Higher-order Function)。
program_options里的這種方式是怎么實現的呢?通過分析boost的源代碼,我們自己來寫個類似的實現看看:
test.h
1 #pragma once
2
3 #include <iostream>
4 using namespace std;
5
6 class Test;
7
8 class Test_easy_init
9 {
10 public:
11 Test_easy_init(Test* owner):m_owner(owner){}
12
13 Test_easy_init & operator () (const char* name);
14 Test_easy_init & operator () (const char* name,int id);
15 private:
16 Test* m_owner;
17 };
18
19
20 class Test
21 {
22 public:
23 void add(const char* name);
24 void add(const char* name,int id);
25
26 Test_easy_init add_some();
27
28 };
test.cpp
1 #include "test.h"
2
3 Test_easy_init & Test_easy_init::operator () (const char* name,int id)
4 {
5
6 m_owner->add(name,id);
7 return *this;
8 }
9
10
11 Test_easy_init & Test_easy_init::operator () (const char* name)
12 {
13
14 m_owner->add(name);
15 return *this;
16 }
17
18 Test_easy_init Test::add_some()
19 {
20 return Test_easy_init(this);
21 }
22
23
24 void Test::add(const char* name)
25 {
26 cout<<"add:"<<name<<endl;
27 }
28
29 void Test::add(const char* name,int id)
30 {
31 cout<<"add:"<<name<<"-"<<id<<endl;
32 }
使用方式:
1 Test t1;
2
3 t1.add_some()
4 ("hello",1)
5 ("no id")
6 ("hello2",2);
是不是很有意思。add_some()方法返回一個Test_easy_init類的對象,Test_easy_init類重載了操作符(),操作符()方法返回Test_easy_init類對象自身的引用。。