boost库 bind/function的使用
生活随笔
收集整理的這篇文章主要介紹了
boost库 bind/function的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Boost::Function 是對函數指針的對象化封裝,在概念上與廣義上的回調函數類似。相對于函數指針,function除了使用自由函數,還可以使用函數對象,甚至是類的成員函數,這個就很強大了哈
#include <boost/function.hpp> #include <boost/bind.hpp> #include <iostream>using namespace std;class TestA {public:void method(){cout<<"TestA: method: no arguments"<<endl;}void method(int a, int b){cout<<"TestA: method: with arguments"<<"value of a is:"<<a <<"value of b is "<<b <<endl;} };void sum(int a, int b) {int sum = a + b;cout<<"sum: "<<sum<<endl; } int main() {boost::function<void()> f;TestA test;f = boost::bind(&TestA::method, &test);f();f = boost::bind(&TestA::method, &test, 1, 2);f();f = boost::bind(&sum, 1, 2);f(); }
2. 應用:Thread封裝
在實現自定義的線程類時,曾經這么干過:定義虛函數run(),用戶自定義的CustomThread::Thread后,自己實現run()函數就OK了。 當時覺得這么做也不錯。
現在有了boost::function/boost::bind我們可以這么干:
定義一個線程類:
.h文件
#include <pthread.h> #include <string> #include <boost/function.hpp> #include <boost/bind.hpp>using namespace std; class Thread {typedef boost::function<void()> ThreadFun;public:Thread(const ThreadFun& threadFun,const string& threadName = string());pid_t getThreadId();string getThreadName();int start();private:static void* startThread(void* thread);private:pthread_t m_thread; //線程句柄pid_t m_tid; //線程IDstring m_strThreadName; //線程名稱bool m_bStarted; //線程是否啟動ThreadFun m_func; //線程處理函數 };
.cpp
#include "thread.h"Thread::Thread(const Thread::ThreadFun& threadFun, const string& threadName): m_func(threadFun), m_strThreadName(threadName) { }int Thread::start() {m_tid = pthread_create(&m_thread, NULL, &startThread, this);return 0; }void* Thread::startThread(void* obj) {Thread* thread = static_cast<Thread*>(obj);thread->m_func();return NULL; }pid_t Thread::getThreadId() {return m_tid; };string Thread::getThreadName() {return m_strThreadName; }
void ThreadProcess() {int count = 100;for (int i = 0; i < count; i++){if (i % 10 == 0) cout<<"\n";cout<<i<<"\t";} }int main() {boost::function<void()> f;f = boost::bind(&ThreadProcess); Thread thread(f, "ThreadTest");thread.start();sleep(1000*1000);return 0; }
| ? | |
轉載于:https://www.cnblogs.com/mtcnn/p/9410077.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的boost库 bind/function的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开心一笑
- 下一篇: 中文字串截取无乱码的问题