C++:回调的思想

/ C++ / 没有评论 / 2055浏览

###类内函数回调利用function模板和std::bind实现类似函数指针的功能,但其比函数指针更加灵活,特别是处理一些类的非静态成员函数时,function模板可以绑定到全局函数或类的静态成员函数,如果要绑定类的非静态成员函数,则需要使用std::bind。

#include "stdafx.h"
#include <Windows.h>
#include <process.h>
#include <functional>
#include <iostream>
#include <time.h>

using namespace std;

typedef std::function<void (int index)> NotifyFun;

class CMgr
{
public:
	CMgr()
	{

	}
	~CMgr()
	{

	}
	void StdCall(int x)
	{
		if (m_pFunc)
		{
			m_pFunc(x);
		}
	}
	void SetCallbcak(NotifyFun pFunc)
	{
		m_pFunc = pFunc;
	}
private:
	NotifyFun m_pFunc;
};


class CUser
{
public:
	CUser(CMgr* pMgr)
		: m_pMgr(pMgr)
	{

	}
	~CUser()
	{
	
	}

	void SetFunc()
	{
		NotifyFun func = std::bind(&CUser::MyFunc, this, std::placeholders::_1);
		m_pMgr->SetCallbcak(func);
	}
	void MyFunc(int x)
	{
		cout<<"CUser::MyFunc:"<<x<<endl;
	}

private:
	CMgr* m_pMgr;
};

unsigned int _stdcall ThreadProc(void* param)
{
	int countIndex = 0;
	CMgr* pMgr = (CMgr*)param;

	srand(time(NULL));
	while (true)
	{
		countIndex++;
		if (countIndex > 10)
		{
			break;
		}

		int x = rand();

		pMgr->StdCall(x);

		Sleep(1 * 1000);
	}

	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	CMgr* pMgr = new CMgr;

	CUser user(pMgr);

	user.SetFunc();

	HANDLE hThread;
	unsigned int threadId;

	hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, pMgr, 0, &threadId);

	WaitForSingleObject(hThread, INFINITE);

	CloseHandle(hThread);

	system("pause");

	return 0;
}