使用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<void(void*, void*)> Handler;
	static int id;
	map<int, Handler> 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 <iostream>

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;
}


结果:

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

原文链接: https://www.cnblogs.com/wmesci/archive/2012/02/05/2735997.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/40985

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午5:52
下一篇 2023年2月8日 下午5:52

相关推荐