c++11 中将类成员函数实现回调

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

欢迎关注问我团队公众号:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值