3.Boost之function
1第一個function案例
#include<iostream>
#include <boost/function.hpp>
?
using namespace std;
using namespace boost;
?
int main(int argc,char *argv[])
{
??? //其中atoi:表示的是將字符串轉換成為數(shù)字,即:char * to int
??? //int表示的是函數(shù)的返回值,char *表示函數(shù)的參數(shù)類型
??? boost::function<int(char *)> fun = atoi;
??? //下面的運行結果是25
??? cout << fun("12") + fun("13") << endl;
?
??? //指向strlen函數(shù)??梢灾苯?span lang="EN-US">=,是因為strlen的參數(shù)類型也是char *類型的
??? fun = strlen;
??? //說明不不加'\0',下面的運行結果是5
??? cout << fun("adfaa") << endl;
?
??? cin.get();
}
運行結果:
2.function結合bind,案例如下:
#include<iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
?
using namespace std;
using namespace boost;
?
int main(int argc, char *argv[])
{
??? boost::function<int(char *)> fun = atoi;
??? //下面的_1是一個占位符,表示fun要傳入的參數(shù)
??? fun = boost::bind(strcmp, "034", _1);
??? //如果上面的"034"改成"234",運行結果是1
??? //此種情況運行的結果是:-1
??? cout << fun("123") << endl;
??? //下面的運行結果是0
??? cout << fun("034") << endl;
?
??? cin.get();
}
運行結果是:
3.function案例3
#include<iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
?
using namespace std;
using namespace boost;
?
//通過下面的類管理worker類
class manager
{
public:
??? void allstart()
??? {
??????? for (int i = 0; i < 10; i++)
??????? {
??????????? //判斷是否為空
??????????? if (workid)
??????????? {
??????????????? //這時候直接調用i
??????????????? workid(i);
??????????? }
??????? }
??? }
??? //綁定調用,類似劫持,回調
??? void setcallback(boost::function<void(int)> newid)
??? {
??????? workid = newid;
??? }
public:
??? //通過下面的指針綁定void run(int toid)這個函數(shù)
??? boost::function<void(int)> workid;
};
?
class worker
{
public:
??? void run(int toid)
??? {
??????? id = toid;
??????? cout << id << "工作" << endl;
??? }
public:
??? int id;
};
?
int main(int argc, char *argv[])
{
??? manager m;
??? worker w;
??? //類的成員函數(shù)需要對象來調用,綁定一個默認的對象
??? //在調用之前要進行一個綁定,綁定到對象之上
??? m.setcallback(boost::bind(&worker::run, &w, _1));
?
??? m.allstart();
?
??? cin.get();
??? return 0;
}
運行結果:
?
?
?
?
?
?
?
?
?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的3.Boost之function的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大宝丝锥M5*0.86G与M5*0.8+
- 下一篇: 4.Boost之ref