传递function_boost库function与bind
boost庫function與bind
一、function 頭文件:boost/function.hpp function更合適的說法我覺得是一種回調函數的表現方式。
boost::function是一個函數對象的“容器”,概念上像是C/C++中函數指針類型的泛化,是一種“智能函數指針”。它以對象的形式封裝了原始的函數指針或函數對象,能夠容納任意符合函數簽名的可調用對象。在聲明 functions 時,聲明中最重要的部分是函數的簽名。這部分即是告訴 function 它將保存的函數或函數對象的簽名和返回類型。
boost::function能夠代替函數指針,并且能能接受函數或函數對象,增加了程序的靈活性。但是boost::function相比函數指針來說體積稍大一點,速度上稍慢一點。
函數原型:boost::function f;
看一個簡單的例子:
#include <iostream> #include <boost/function.hpp> #include <boost/bind.hpp>typedef boost::function<int(int,char)>Func;int test(int num,char ch) {std::cout<<num<<" "<<ch<<std::endl; }int main() {Func f;f = &test;f(1,'a');return 0; }//回調函數結果是:
localhost@localhost:/mnt/hgfs/share/boost$ ./function 1 a二、bind 頭文件:boost/bind.hpp
bind的基本形式如下:
template<class R,class F> bind(F f); template<class R,class F,class A1> bind(F f,A1 a1); namespace { boost::arg<1> _1; boost::arg<2> _2; boost::arg<3> _3; ….. //其他6個占位符 };bind接收的第一個參數必須是一個可調用的對象f,包括函數、函數指針、函數對象、和成員函數指針,之后bind最多接受9個參數,參數數量必須與f的參數數量相等,這些參數被傳遞給f作為入參。 綁定完成后,bind會返回一個函數對象,它內部保存了f的拷貝,具有operator(),返回值類型被自動推導為f的返回類型。在發生調用時這個函數對象將把之前存儲的參數轉發給f完成調用。例如,有一個函數func,它的形式是:
1 func(a1,a2);那么,他將等價于一個具有無參operator()的bind函數對象調用:
1 bind(func,a1,a2)();這是bind最簡單的形式,bind表達式存儲了func和a1、a2的拷貝,產生了一個臨時函數對象。因為func接收兩個參數,而a1和a2的拷貝傳遞給func完成真正的函數調用。
bind的真正威力在于它的占位符,它們分別定義為_1,_2,_3,一直到 _9,位于一個匿名的名字空間。占位符可以取代bind參數的位置,在發生調用時才接受真正的參數。占位符的名字表示它在調用式中的順序,而在綁定的表達式中沒有沒有順序的要求,_1不一定必須第一個出現,也不一定只出現一次,例如:
1 bind(func,_2,_1)(a1,a2);返回一個具有兩個參數的函數對象,第一個參數將放在func的第二個位置,而第二個參數則放在第一個位置,調用時等價于:
1 func(a2,a1);看一下例子:
#include <functional> #include <iostream> #include <string> #include "boost/bind.hpp"void print_string(const std::string s) { std::cout << s << 'n'; } void print_functionname() {std::cout << "Print_functionname" <<std::endl; }int main() {boost::bind(print_functionname)();return 0; }結果:
localhost@localhost:/mnt/hgfs/share/boost$ ./bind Print_functionname包含類的例子:
#include <functional> #include <iostream> #include <string> #include "boost/bind.hpp" class Test { public: void print_string(const std::string& s) const{ std::cout << s << 'n'; }void print(){std::cout << "Test" << std::endl;} };int main() {Test ts;boost::bind(&Test::print,_1)(ts);boost::bind(&Test::print_string,_1,_2)(ts,"hello Test");return 0; }結果:
localhost@localhost:/mnt/hgfs/share/boost$ ./bind Test hello Test三、function與bind聯合使用 一般bind和function會在一起使用,這里只寫一個簡單的例子
#include <iostream> #include <boost/bind.hpp> #include <boost/function.hpp>typedef boost::function<void(void)>Func;void print_string(const std::string s) {std::cout<<"s:"<<s<<std::endl; }int main() {Func f(boost::bind(print_string,"hello bind"));f();return 0; }結果:
localhost@localhost:/mnt/hgfs/share/boost$ ./bind1 s:hello bind參考文章:https://www.cnblogs.com/blueoverflow/p/4740093.html
想了解學習更多C++后臺服務器方面的知識,請關注: 微信公眾號:====C++后臺服務器開發====
總結
以上是生活随笔為你收集整理的传递function_boost库function与bind的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 代码 抠图_067,我学会了用代码来抠图
- 下一篇: access 日期交集_Access重要