使用C++0x function & bind实现的事件

#pragma once
#include 
#include 

using namespace std;

#define delegate(t, f) std::bind(f, t, std::tr1::placeholders::_1, std::tr1::placeholders::_2);

class event
{
private:
	typedef function Handler;
	static int id;
	map list;

public:
	int operator +=(Handler f)
	{
		this->list[++id] = f;
		return id;
	}

	void operator -=(int id)
	{
		this->list.erase(id);
	}

	void operator()(void* sender, char* e)
	{
		for each(auto f in list)
			f.second(sender, e);
	}
};


测试代码:

#include "stdafx.h"
#include "Event.h"
#include 

class TestA
{
public:
	void handler(void* sender, char* e)
	{
		std::cout<<"TestA.Handler\r\n";
	}
};

class TestB
{
public:
	event OnEvent;

	void Raise(char* str)
	{
		OnEvent(NULL, str);
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	TestA a;
	TestB b;
	b.OnEvent += delegate(&a, &TestA::handler);
	b.Raise();
	system("PAUSE");
	return 0;
}

 
   


结果:




转载于:https://www.cnblogs.com/wmesci/archive/2012/02/05/2735997.html

你可能感兴趣的:(c/c++)