bind是这样一种机制,它可以预先把指定可调用实体的某些参数绑定到已有的变量,产生一个新的可调 用实体,这种机制在回调函数的使用过程中也颇为有用。其实最早在C++98的时候,就已经有了std::bind1st和std::bind2nd分别用来绑定functor的两个参数,具体代码就不演示了,查查资料就知道了。这个特性在当时并没有引起太多的重视,可以说是食之无味。
C++11中提供了std::bind,可以说是一种飞跃的提升,bind本身是一种延迟计算的思想,它本身可以绑定普通函数、全局函数、静态函数、类静态函数甚至是类成员函数。
bind最终将会生成一个可调用对象,这个对象可以直接赋值给std::function对象,而std::bind绑定的可调用对象可以是Lambda表达式或者类成员函数等可调用对象,它能随意绑定任何函数,将所有的函数都能统一到std::function
#include <iostream>
#include <string>
#include <stdlib.h>
#include <functional>
using namespace std;
using namespace std::placeholders;
class MyClass
{
public:
MyClass();
~MyClass();
public:
void testFunc(int num)
{
cout << "num = " << num << endl;
cout << "test sucess" << endl;
}
private:
};
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
typedef void(*callBack)(void* args);
typedef std::function<void(int)> Fun;
struct MyStruct
{
int num;
Fun testFunc;
};
void myCallBack(void* args)
{
MyStruct* mystruct = (MyStruct*)args;
mystruct->testFunc(mystruct->num);
}
int main()
{
MyClass* testClass = new MyClass;
MyStruct* testStruct = new MyStruct;
testStruct->num = 1;
testStruct->testFunc = std::bind(&MyClass::testFunc, testClass,_1);
//void* testarg = (void*)&testStruct;
//myCallBack(testarg);
callBack test = myCallBack;
test(testStruct);
return 0;
}
参考博客:
http://blog.csdn.net/xyblog/article/details/50314515 作者:xyblog
http://blog.csdn.net/hyp1977/article/details/51784520 作者:小胡_uYou