C++实现委托机制之完整代码实现

头文件 MyDelegate.h 代码如下:

#pragma once

#include <typeinfo.h>
#include <list>
#include <vector>

namespace Delegate
{

	// IDelegate   提供接口的基类

	template<typename ReturnType, typename ...ParamType>
	class IDelegate
	{
	public:
		IDelegate(){}
		virtual ~IDelegate(){}
		virtual bool isType(const std::type_info& _type) = 0;
		virtual ReturnType invoke(ParamType ... params) = 0;
		virtual bool compare(IDelegate<ReturnType, ParamType...> *_delegate) const = 0;
	};

	
	//StaticDelegate 普通函数的委托

	template<typename ReturnType, typename ...ParamType>
	class CStaticDelegate :
		public IDelegate<ReturnType, ParamType...>
	{
	public:

		typedef  ReturnType(*Func)(ParamType...);

		CStaticDelegate(Func _func) : mFunc(_func) { }

		virtual bool isType(const std::type_info& _type) { return typeid(CStaticDelegate<ReturnType, ParamType...>) == _type; }

		virtual ReturnType invoke(ParamType ... params) { return mFunc(params...); }

		virtual bool compare(IDelegate<ReturnType, ParamType ...> *_delegate)const
		{
			if (0 == _delegate || !_delegate->isType(typeid(CStaticDelegate<ReturnType, ParamType ...>))) return false;
			CStaticDelegate<ReturnType, ParamType ...> * cast = static_cast<CStaticDelegate<ReturnType, ParamType ...>*>(_delegate);
			return cast->mFunc == mFunc;
		}

		virtual ~CStaticDelegate(){}
	private:
		Func mFunc;
	};


	//普通函数的委托特化版本
	template<typename ReturnType, typename ...ParamType>
	class CStaticDelegate<ReturnType(*)(ParamType ...)> :
		public IDelegate<ReturnType, ParamType ...>
	{
	public:

		//定义 Func 为 void (void) 函数类型指针。
		typedef  ReturnType(*Func)(ParamType...);

		CStaticDelegate(Func _func) : mFunc(_func) { }

		virtual bool isType(const std::type_info& _type) { return typeid(CStaticDelegate<ReturnType(*)(ParamType ...)>) == _type; }

		virtual ReturnType invoke(ParamType ... params) { return mFunc(params...); }

		virtual bool compare(IDelegate<ReturnType, ParamType ...> *_delegate)const
		{
			if (0 == _delegate || !_delegate->isType(typeid(CStaticDelegate<ReturnType(*)(ParamType ...)>))) return false;
			CStaticDelegate<ReturnType(*)(ParamType ...)> * cast = static_cast<CStaticDelegate<ReturnType(*)(ParamType ...)>*>(_delegate);
			return cast->mFunc == mFunc;
		}

		virtual ~CStaticDelegate(){}
	private:
		Func mFunc;
	};

	//成员函数委托
	template<typename T, typename ReturnType, typename ...ParamType>
	class CMethodDelegate :
		public IDelegate<ReturnType, ParamType...>
	{
	public:
		typedef ReturnType(T::*Method)(ParamType...);

		CMethodDelegate(T * _object, Method _method) : mObject(_object), mMethod(_method) { }

		virtual bool isType(const std::type_info& _type) { return typeid(CMethodDelegate<T, ReturnType, ParamType...>) == _type; }

		virtual ReturnType invoke(ParamType...params)
		{
			(mObject->*mMethod)(params...);
		}

		virtual bool compare(IDelegate<ReturnType, ParamType...> *_delegate) const
		{
			if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate<ReturnType, ParamType...>))) return false;
			CMethodDelegate<ReturnType, ParamType...>* cast = static_cast<CMethodDelegate<ReturnType, ParamType...>*>(_delegate);
			return cast->mObject == mObject && cast->mMethod == mMethod;
		}

		CMethodDelegate(){}
		virtual ~CMethodDelegate(){}
	private:
		T * mObject;
		Method mMethod;
	};

	//成员函数委托特化
	template<typename T, typename ReturnType, typename ...ParamType>
	class CMethodDelegate<T,ReturnType (T:: *)(ParamType...)> :
		public IDelegate<ReturnType, ParamType...>
	{
	public:
		typedef ReturnType(T::*Method)(ParamType...);

		CMethodDelegate(T * _object, Method _method) : mObject(_object), mMethod(_method) { }

		virtual bool isType(const std::type_info& _type) { return typeid(CMethodDelegate<T,ReturnType(T:: *)(ParamType...)>) == _type; }

		virtual ReturnType invoke(ParamType...params)
		{
			return (mObject->*mMethod)(params...);
		}

		virtual bool compare(IDelegate<ReturnType, ParamType...> *_delegate) const
		{
			if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate<T, ReturnType(T:: *)(ParamType...)>))) return false;
			CMethodDelegate<T, ReturnType(T:: *)(ParamType...)>* cast = static_cast<CMethodDelegate<T, ReturnType(T:: *)(ParamType...)>*>(_delegate);
			return cast->mObject == mObject && cast->mMethod == mMethod;
		}

		CMethodDelegate(){}
		virtual ~CMethodDelegate(){}
	private:
		T * mObject;
		Method mMethod;
	};

	


	//多播委托
	template<typename ReturnType, typename ...ParamType>
	class CMultiDelegate
	{
		
	public:
		
		typedef std::list<IDelegate<ReturnType, ParamType...>*> ListDelegate;
		typedef typename ListDelegate::iterator ListDelegateIterator;
		typedef typename ListDelegate::const_iterator ConstListDelegateIterator;

		CMultiDelegate() { }
		~CMultiDelegate() { clear(); }

		bool empty() const
		{
			for (ConstListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)
			{
				if (*iter) return false;
			}
			return true;
		}

		void clear()
		{
			for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)
			{
				if (*iter)
				{
					delete (*iter);
					(*iter) = nullptr;
				}
			}
		}


		CMultiDelegate<ReturnType, ParamType...>& operator+=(IDelegate<ReturnType, ParamType...>* _delegate)
		{
			for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)
			{
				if ((*iter) && (*iter)->compare(_delegate))
				{
					delete _delegate;
					return *this;
				}
			}
			mListDelegates.push_back(_delegate);
			return *this;
		}

		CMultiDelegate<ReturnType, ParamType...>& operator-=(IDelegate<ReturnType, ParamType...>* _delegate)
		{
			for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)
			{
				if ((*iter) && (*iter)->compare(_delegate))
				{
					if ((*iter) != _delegate) delete (*iter);       //避免同一个地址被delete两次
					(*iter) = 0;
					break;
				}
			}
			delete _delegate;
			return *this;
		}

		std::vector<ReturnType> operator()(ParamType... params)
		{
			ListDelegateIterator iter = mListDelegates.begin();
			std::vector<ReturnType> _Results;
			while (iter != mListDelegates.end())
			{
				if (0 == (*iter))
				{
					iter = mListDelegates.erase(iter);
				}
				else
				{
					_Results.push_back((*iter)->invoke(params...));
					++iter;
				}
			}
			return _Results;
		}
	private:
		CMultiDelegate<ReturnType, ParamType...>(const CMultiDelegate& _event);
		CMultiDelegate<ReturnType, ParamType...>& operator=(const CMultiDelegate& _event);

	private:
		ListDelegate mListDelegates;
	};

	template< typename ...ParamType>
	class CMultiDelegate<void, ParamType...>
	{

	public:

		typedef std::list<IDelegate<void, ParamType...>*> ListDelegate;
		typedef typename ListDelegate::iterator ListDelegateIterator;
		typedef typename ListDelegate::const_iterator ConstListDelegateIterator;

		CMultiDelegate() { }
		~CMultiDelegate() { clear(); }

		bool empty() const
		{
			for (ConstListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)
			{
				if (*iter) return false;
			}
			return true;
		}

		void clear()
		{
			for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)
			{
				if (*iter)
				{
					delete (*iter);
					(*iter) = nullptr;
				}
			}
		}

		CMultiDelegate<void, ParamType...>& operator+=(IDelegate<void, ParamType...>* _delegate)
		{
			for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)
			{
				if ((*iter) && (*iter)->compare(_delegate))
				{
					delete _delegate;
					return *this;
				}
			}
			mListDelegates.push_back(_delegate);
			return *this;
		}

		CMultiDelegate<void, ParamType...>& operator-=(IDelegate<void, ParamType...>* _delegate)
		{
			for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)
			{
				if ((*iter) && (*iter)->compare(_delegate))
				{
					if ((*iter) != _delegate) delete (*iter);       //避免同一个地址被delete两次
					(*iter) = 0;
					break;
				}
			}
			delete _delegate;
			return *this;
		}

		void operator()(ParamType... params)
		{
			ListDelegateIterator iter = mListDelegates.begin();
			while (iter != mListDelegates.end())
			{
				if (0 == (*iter))
				{
					iter = mListDelegates.erase(iter);
				}
				else
				{
					(*iter)->invoke(params...);
					++iter;
				}
			}
		}
	private:
		CMultiDelegate<void, ParamType...>(const CMultiDelegate& _event);
		CMultiDelegate<void, ParamType...>& operator=(const CMultiDelegate& _event);

	private:
		ListDelegate mListDelegates;
	};





	template< typename T>
	CStaticDelegate<T>* newDelegate(T func)
	{
		return new CStaticDelegate<T>(func);
	}
	template< typename T,typename F>
	CMethodDelegate<T,F>* newDelegate(T * _object, F func)
	{
		return new CMethodDelegate<T, F>(_object, func);
	}
}


源文件 main.cpp 代码如下:

int _tmain(int argc, _TCHAR* argv[])
{
	CMultiDelegate<void,int> e;              //void(int)

	e += newDelegate([](int a){ printf("这是lambda表达式\n"); });  //请尽量不要使用这种方式。
	e -= newDelegate([](int a){ printf("这是lambda表达式\n"); });  //这样是无法注销的。因为上面那个lambda表达式和下面这个类型不一样!!
	//请使用下面这种方式:
	auto func = newDelegate([](int a){ printf("这是lambda表达式\n"); });;

	e += func;
	e -= func;

	return 0;
}


C++ 并没有原生的委托机制,但可以通过函数指针和对象指针来模拟委托机制。 在 C++ 中,函数指针可以作为参数传递和返回值,可以使用函数指针来实现委托的功能。而对象指针可以用于保存对象的状态和数据,也可以用于调用对象的成员函数。 以下是一个简单的 C++ 示例代码,演示了如何通过函数指针和对象指针来实现委托机制: ```cpp #include <iostream> #include <functional> using namespace std; class Delegate { public: void (*func)(void*); // 函数指针 void* obj; // 对象指针 void Invoke() { func(obj); // 调用函数指针 } }; class Test { public: void Print() { cout << "Hello, world!" << endl; } }; void PrintTest(void* obj) { Test* test = (Test*)obj; // 将对象指针转换为 Test 类型指针 test->Print(); // 调用对象的成员函数 } int main() { Test test; Delegate delegate; delegate.func = PrintTest; delegate.obj = &test; delegate.Invoke(); // 调用委托 return 0; } ``` 在这个示例代码中,我们定义了一个 `Delegate` 类,其中包含了一个函数指针和一个对象指针。`Invoke` 函数用于调用委托。我们还定义了一个 `Test` 类,其中包含了一个成员函数 `Print`。在 `main` 函数中,我们创建了一个 `Test` 对象 `test`,并创建了一个 `Delegate` 对象 `delegate`,将 `PrintTest` 函数的地址和 `test` 对象的地址分别赋值给 `Delegate` 对象的函数指针和对象指针。最后,我们通过 `delegate.Invoke()` 调用委托,实际上就是调用了 `PrintTest` 函数,并将 `test` 对象传递给了该函数,从而调用了 `Test` 对象的 `Print` 成员函数。 需要注意的是,这只是一个简单的示例,实际的委托机制可能更加复杂,并且需要考虑线程安全等问题。如果需要使用委托机制,建议使用现有的 C++ 第三方库或框架,如 Boost、Qt 等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值