boost bind/function库的使用:
替换了stl中mem_fun,bind1st,bin2nd等函数。用户注册回调函数需要利用boost/bind转化成库中boost/function格式的函数。然后调用库的时候就可以回调用户注册的处理函数了。bind也可以将成员函数转换成boost/function指定的函数格式。
#include<iostream> #include<boost/function.hpp> #include<boost/bind.hpp> using namespace std; class Foo { public: void memberFunc(double d,int i,int j) { cout << d << endl; cout << i << endl; cout << j << endl; } }; int main() { Foo foo; //将一种函数类型的接口转换为另一种函数类型的接口。 //将这个成员函数&Foo::memberFuncvoid适配成void f(int)这样的接口。 //成员函数有4个参数this d i j,适配成的函数接口有一个参数。 boost::function<void(int)> fp = boost::bind(&Foo::memberFunc,&foo/*this指针参数*/,0.5,_1,10); fp(100); boost::function<void(int,int)> fp = boost::bind(&Foo::memberFunc, &foo, 0.5, _1, _2); fp(100,200); return 0; }
利用boost bind/function实现基于对象的Thread类:
#ifndef _THREAD_H_ #define _THREAD_H_ #include <pthread.h> class { public: typedef boost::function(void()) ThreadFunc; explicit Thread(const ThreadFunc& func);//阻止隐式转换构造。 void Start(); void Join(); void SetAutoDelete(bool autoDelete); private: static void* ThreadRoutine(void* arg); void Run(); ThreadFunc func_; pthread_t threadId_; bool autoDelete_; }; #endif
//基于对象的方法编写Thread类。 /* Start()、Join()、ThreadRoutine(void* arg)线程入口函数调用Run()、Run()执行体函数。 typedef boost::function<void()> ThreadFunc; 面向对象的方法中:线程的执行体函数由派生类Run()方法来覆盖积累中的Run()来实现。 基于对象时:线程的执行体函数由构造函数传入ThreadFunc方法。Run()调用这个ThreadFunc(); */ #include"Thread.h" #include<iostream> using namespace std; Thread::Thread(const ThreadFunc& func):autoDelete_(false),func_(func) { cout << "Thread..." << endl; } Thread()::~Thread() { cout << "~Thread..." << endl; } void Thread::Start() { pthread_create(&threadId_,NULL,ThreadRoutine,this); } void Thread::Join() { pthread_join(threadId_,NULL); } void ThreadRoutine(void* arg) { Thread* thread = static_cast<Thread*>(arg); thread->Run(); if (thread->autoDelete_) delete thread; return NULL; } void Thread::SetAutoDelete(bool autoDelete) { autoDelete_ = autoDelete; } void Thread::Run() { func_(); }
void ThreadFunc(int count) { cout << "threadfunc" << endl; } int main(void) { Thread t1(boost::bind(ThreadFunc,3)); t1.Start(); t1.Join(); return 0; }