boost::bind 介绍
boost::bind 介紹
?? ?這篇文章介紹boost::bind()的用法, 文章的主要內(nèi)容是參考boost的文檔。
1. 目的
?? boost::bind 是std::bindlist 和 std::bind2nd的結(jié)合體。它提供一個(gè)任意的函數(shù)對(duì)象(仿函數(shù))、函數(shù)、函數(shù)指針、成員函數(shù)指針。 它可以綁定任意的參數(shù)。bind 沒有對(duì)函數(shù)對(duì)象有任何的要求。
2. 把bind()用在函數(shù)和函數(shù)指針上
??? 有如下代碼:
?
1 void f(int a, int b) 2 { 3 cout << a + b << endl; 4 } 5 ?void g(int a, int b, int c) 6 { 7 cout << a + b + c << endl;; 8 }?
??? 當(dāng)調(diào)用boost::bind(f, 1, 2);的時(shí)候, 它會(huì)產(chǎn)生一個(gè)空的函數(shù)對(duì)象,這個(gè)對(duì)象沒有參數(shù), 返回 f(1,2).當(dāng)然我們也可以給它加個(gè)參數(shù):
?
1 int a = 10; 2 boost::bind(f, _1, 5)(a); 3 int x(10),y(20),z(30); 4 boost::bind(g,_1,_2,_3)(x, y, z);?
??? 結(jié)果:
??? 作為和std::bindlst的對(duì)比我們可以看下如下的代碼:
1 std::bind1st(std::ptr_fun(f), 5)(x); // f(5, x) 2 boost::bind(f, 5, _1)(x); // f(5, x)??? 是不是boost::bind()簡單多了。
3. 把bind()用在函數(shù)對(duì)象(仿函數(shù))上
??? bind()不僅能夠用在函數(shù)上,而且可以接受任意的函數(shù)對(duì)象(仿函數(shù))。如:
?
1 class F 2 { 3 public: 4 int operator()(int a, int b) 5 { 6 cout << a+b <<endl; 7 return a+b; 8 } 9 double operator()(double a, double b) 10 { 11 cout << a+b<< endl; 12 return a +b; 13 } 14 }; 15 int _tmain(int argc, _TCHAR* argv[]) 16 { 17 F f; 18 int a[] = {1, 2, 3, 4, 5, 6,7}; 19 double aDouble[] = {1.1, 2.2, 3.3, 4.4,5.5,6.6,7.7}; 20 for_each(a, a+7, boost::bind<int>(f, _1, _1)); 21 for_each(aDouble, aDouble+7, boost::bind<double>(f, _1, _1)); 22 return 0; 23 }?
4. 把bind()用在成員變量和成員函數(shù)上
??? 指向成員變量的指針和指向成員函數(shù)的指針和仿函數(shù)不一樣, 因?yàn)樗麄儧]有提供operater()。boost用它的第一個(gè)參數(shù)接受類成員的指針,這樣就像用boost::mem_fn()把類成員的指針轉(zhuǎn)化為仿函數(shù)一樣。如:
bind(&X::f, args)就等于
bind<R>(mem_fn(&X::f), args)//R 是x::f的返回值。 列如:?
1 struct X 2 { 3 bool f(int a) 4 { 5 cout << a <<endl; 6 return static_cast<bool>(a); 7 } 8 }; 9 int _tmain(int argc, _TCHAR* argv[]) 10 { 11 X x; 12 boost::shared_ptr<X> p(new X); 13 int i = 5; 14 boost::bind(&X::f, &x, _1)(i); // (&x)->f(i); 15 boost::bind(&X::f, x, _1)(i); //(copy x).f(i); 16 boost::bind(&X::f, p, _1)(i); //(copy p)->f(i); 17 return 0; 18 }?
?? ?boost::bind()的基本用法就這些, 在使用的過程中發(fā)現(xiàn)確實(shí)比較爽, 但是這不知道這是不是常常被人批判的語法糖。
總結(jié)
以上是生活随笔為你收集整理的boost::bind 介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下 open() write(
- 下一篇: c++ Boost库之boost::bi