function是函数包装器,bind可以绑定普通函数和类成员函数。
当function的返回值和形成都被声明为void时,可以接收被bind修饰的任意函数类型。
如:
#include "boost/function.hpp"
#include "boost/bind.hpp"
#include <iostream>
class Task
{
public:
bool Bind(boost::function<void()> func)
{
if (func)
{
m_fun = func;
return true;
}
return false;
}
void Process(){ m_fun(); }
private:
boost::function<void()> m_fun;
};
void Func1()
{
std::cout << __FUNCTION__ << std::endl;
}
void Func2(int i)
{
std::cout << __FUNCTION__ << std::endl;
std::cout << "i: " << i << std::endl;
}
bool Func3(bool b)
{
std::cout << __FUNCTION__ << std::endl;
return b;
}
void TestFunc()
{
Task task;
task.Bind(boost::bind(Func1));
task.Process();
task.Bind(boost::bind(Func2, 10));
task.Process();
task.Bind(boost::bind(Func3, true));
task.Process();
}