boost::function的用法(一)
boost::function的用法
本片文章主要介紹boost::function的用法。 boost::function 就是一個(gè)函數(shù)的包裝器(function wrapper),用來定義函數(shù)對(duì)象。
1.? 介紹
??? Boost.Function 庫包含了一個(gè)類族的函數(shù)對(duì)象的包裝。它的概念很像廣義上的回調(diào)函數(shù)。其有著和函數(shù)指針相同的特性但是又包含了一個(gè)調(diào)用的接口。一個(gè)函數(shù)指針能夠在能以地方被調(diào)用或者作為一個(gè)回調(diào)函數(shù)。boost.function能夠代替函數(shù)指針并提供更大的靈活性。
2. 使用
??? Boost.Function 有兩種形式:首選形式和便攜式形式, 其語法如下:
| 首選形式 | 便攜式形式 |
| boost::function<float(int x, int y)>f | boost::function2<float, int, int>f |
但是便攜式形式不是所有的編譯器都支持的, 所以這里我只介紹首選形式。
2.1 普通函數(shù)
??? 我們可以看下如下的例子:
1 void do_sum(int *values, int n) 2 2 { 3 3 int sum(0); 4 4 for (int i = 0; i < n; ++i) 5 5 { 6 6 sum += values[i]; 7 7 } 8 8 cout << sum << endl; 9 9 }; 10 10 int _tmain(int argc, _TCHAR* argv[]) 11 11 { 12 12 boost::function<void(int *values, int n)> sum; 13 13 sum = &do_sum; 14 14 int a[] = {1,2,3,4,5}; 15 15 sum(a, 5); 16 16 return 0; 17 17 }?
?
? sum 可以理解為一個(gè)廣義的函數(shù)對(duì)象了,其只用就是保存函數(shù)do_sum, 然后再調(diào)用之。
2.2 成員函數(shù)
??? 在很多系統(tǒng)中, 對(duì)于類的成員函數(shù)的回調(diào)需要做特殊處理的。這個(gè)特殊的處理就是“參數(shù)綁定”。當(dāng)然這個(gè)超出了我們討論的范圍了。 boost::function對(duì)于成員函數(shù)的使用可以看下如下代碼:
1 class X{ 2 2 public: 3 3 int foo(int a) 4 4 { 5 5 cout << a <<endl; 6 6 return a; 7 7 } 8 8 }; 9 9 int _tmain(int argc, _TCHAR* argv[]) 10 10 { 11 11 boost::function<int(X*, int)>f; 12 12 f = &X::foo; 13 13 X x; 14 14 f(&x, 5); 15 15 return 0; 16 16 }?
?
??? 我們發(fā)現(xiàn), 對(duì)類的成員函數(shù)的對(duì)象化從語法是沒有多大的區(qū)別。
3. 一個(gè)典型的例子
??? 上面的幾個(gè)例子沒有體現(xiàn)出boost::function的作用來, 這里在寫一個(gè)例子。比如當(dāng)程序執(zhí)行到某一處的時(shí)候想綁定某一個(gè)函數(shù), 但是不想立即執(zhí)行, 我們就可以聲明一個(gè)函數(shù)對(duì)象,給此對(duì)象綁定相應(yīng)的函數(shù), 做一些其他事情,然后再來執(zhí)行綁定的函數(shù), 代碼如下:
1 void print(int a) 2 2 { 3 3 cout << a << endl; 4 4 } 5 5 typedef boost::function<void (int)> SuccessPrint; 6 6 int _tmain(int argc, _TCHAR* argv[]) 7 7 { 8 8 vector<SuccessPrint> printList; 9 9 SuccessPrint printOne = boost::bind(print, _1); 10 10 printList.push_back(printOne); 11 11 SuccessPrint printTwo = boost::bind(print, _1); 12 12 printList.push_back(printTwo); 13 13 SuccessPrint printThree = boost::bind(print, _1); 14 14 printList.push_back(printTwo); 15 15 // do something else 16 16 for (int i = 0; i < printList.size(); ++i) 17 17 printList.at(i)(i); 18 18 return 0; 19 19 }?
???? 上述代碼中首先把聲明一個(gè)函數(shù)對(duì)象 typedef boost::function<void (int)> SuccessPrint, 然后把print綁定到斥對(duì)象中, 放入vector中, 到最后才來執(zhí)行這print()函數(shù)。
總結(jié)
以上是生活随笔為你收集整理的boost::function的用法(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql 为什么要用where 1=1或者
- 下一篇: electron 软件 出现进程 XXX