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; //线程ID
string 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;
}
 



最新文章

  1. 自定义Toast解决快速点击时重复弹出,排队无止尽
  2. WWDC 2013 Session笔记 - UIKit Dynamics入门
  3. HTML5 review
  4. js获取浏览器地址
  5. bodyParser注意“需要请求头的支持”
  6. android FragmentPagerAdapter getItem方法没有执行
  7. C# 超时类
  8. SPSS时间序列:频谱分析
  9. 在WPF程序中将控件所呈现的内容保存成图像(转载)
  10. Excel转换成PDF
  11. python运算符的优先级
  12. wget命令解析
  13. xslt中的常用函数
  14. while和for可以相互转换例子
  15. android multicast 多播(组播)问题
  16. JAVA基础--接口 interface
  17. 从并发处理谈PHP进程间通信(二)System V IPC
  18. 用Angular2+Express快速搭建博客
  19. Entity Framework : The model backing the &#39;&#39; context has changed since the database was created
  20. 4.BN推导

热门文章

  1. 剑指offer 面试36题
  2. 高阶函数,map,filter,sorted
  3. MYSQL:基础—主键
  4. TOGAF和BABOK
  5. Python学习进程(6)函数
  6. Python学习进程(5)Python语法
  7. yii框架的中的一些使用介绍
  8. 键盘keyCode
  9. CSS3 3D发光切换按钮
  10. iOS_多线程(二)