C++ 信号槽机制(STL泛型编程)

简介

利用宏和模版实现简单的值修改,触发信号,调用指定函数,可以参考学习以及自行扩展,造轮子。


源码

#include 
#include 
using namespace std;

template
class slotbase
{
public:
	virtual void Execute(T1 para) = 0;
};

template
class slotimpl : public slotbase
{
public:
	slotimpl(T* pObj, void (T::*pMemberFunc)(T1))
	{
		m_pObj = pObj;
		m_pMemberFunc = pMemberFunc;
	}
	virtual void Execute(T1 para)
	{
		(m_pObj->*m_pMemberFunc)(para);
	}
private:
	T* m_pObj;
	void (T::*m_pMemberFunc)(T1);
};

template
class slot
{
public:
	template
	slot(T* pObj, void (T::*pMemberFunc)(T1))
	{
		m_pSlotbase = new slotimpl(pObj, pMemberFunc);
	}
	~slot()
	{
		delete m_pSlotbase;
	}
	void Execute(T1 para)
	{
		m_pSlotbase->Execute(para);
	}
private:
	slotbase* m_pSlotbase;
};

template
class signal
{
public:
	template
	void bind(T* pObj, void (T::*pMemberFunc)(T1 para))
	{
		m_slots.push_back(new slot(pObj, pMemberFunc));
	}
	~signal()
	{
		vector* >::iterator ite = m_slots.begin();
		for (; ite != m_slots.end(); ite++)
		{
			delete *ite;
		}
	}
	void operator()(T1 para)
	{
		vector* >::iterator ite = m_slots.begin();
		for (; ite != m_slots.end(); ite++)
		{
			(*ite)->Execute(para);
		}
	}

private:
	vector* > m_slots;
};

#define CONNECT(sender,signal,receiver,slot)  sender.signal.bind(receiver,slot)

class receiver
{
public:
	void callback1(int a)
	{
		cout << "receiver1: " << a << endl;
	}
};
class receiver2
{
public:
	void callback2(int a)
	{
		cout << "receiver2: " << a << endl;
	}
};

class sender
{
public:
	sender() : m_value(0)  {}
	int get_value()
	{
		return m_value;
	}
	void set_value(int new_value)
	{
		if (new_value != m_value)
		{
			m_value = new_value;
			m_valueChanged(new_value);
		}
	}
	signal m_valueChanged;
private:
	int m_value;

};

int main(int argc, char** arg)
{
	receiver r;
	receiver2 r2;
	sender s;
	CONNECT(s, m_valueChanged, &r, &receiver::callback1);
	CONNECT(s, m_valueChanged, &r2, &receiver2::callback2);
	s.set_value(1);
	system("pause");
	return 0;
}


你可能感兴趣的:(C/C++,《C++,必知必会》)