首页 > 编程语言 >C++ 委托实现

C++ 委托实现

时间:2024-11-07 20:09:44浏览次数:1  
标签:return mListDelegates 委托 virtual 实现 iter C++ CMultiDelegate delegate

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) = delete;
		CMultiDelegate<ReturnType, ParamType...>& operator=(const CMultiDelegate& _event) = delete;

	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) = delete;
		CMultiDelegate<void, ParamType...>& operator=(const CMultiDelegate& _event) = delete;

	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

#include "MyDelegate.h"  

using namespace Delegate;

void NormalFunc(int a)
{
    printf("这里是普通函数 :%d\n", a);
}

int Int_NormalFunc(int a)
{
    printf("这里是普通函数,返回值 :%d\n", a);
    return a;
}

class A
{
public:
    static void StaticFunc(int a)
    {
        printf("这里是成员静态函数 : %d\n", a);
    }
    void MemberFunc(int a)
    {
        printf("这里是成员非静态函数 : %d\n", a);
    }

    int Int_MemberFunc(int a)
    {
        printf("这里是成员非静态函数 ,返回值: %d\n", a);
        return a;
    }
};


int main(int argc, char* argv[])
{
    //首先创建了一个返回值为 void ,参数为int 的一个委托。  
    CMultiDelegate<void, int> e;
    //将三个函数注册到该委托中  
    e += newDelegate(NormalFunc);
    e += newDelegate(A::StaticFunc);
    e += newDelegate(&A(), &A::MemberFunc);

    //调用  
    e(1);

    CMultiDelegate<int, int> inv;
    inv += newDelegate(Int_NormalFunc);
    inv += newDelegate(&A(), &A::Int_MemberFunc);
    inv(200);

    getchar();
    return 0;
}  

输出:

这里是普通函数 :1
这里是成员静态函数 : 1
这里是成员非静态函数 : 1
这里是普通函数,返回值 :200
这里是成员非静态函数 ,返回值: 200




源自:

C++实现委托机制(一) :https://blog.csdn.net/y1196645376/article/details/51408114

C++实现委托机制(二):https://blog.csdn.net/y1196645376/article/details/51416043

标签:return,mListDelegates,委托,virtual,实现,iter,C++,CMultiDelegate,delegate
From: https://www.cnblogs.com/huvjie/p/18533878

相关文章

  • 【IPTV/IPTVnator】集合开源工具 TV 和 iptvnator 实现 IPTV 播放源的成功更新及直播
    文章目录前言一、资源说明1、iptvnator2、TV二、下载工具1、下载TV工具2、下载IPTVnator三、使用步骤1、更新iptv数据源A、默认测速方式B、使用ffmpeg作为测速工具2、使用iptvnator播放iptv数据源3、使用vlc工具播放iptv数据源四、iptvnator修改为v......
  • golang oom监控实现
    packagemainimport( "bytes" "fmt" "io/ioutil" "os" "golang.org/x/sys/unix")funcmain(){ varevents[128]unix.EpollEvent varbuf[8]byte //unix.EFD_CLOEXEC确保在exec调用时关闭efd,它可以防止文件描述符在不需......
  • C++之map容器
    map是C++STL(StandardTemplateLibrary)中的一种关联容器,用于存储键值对(key-valuepairs)。每个键(key)在map中都是唯一的,并且键值对会根据键的值进行排序(默认为升序)。map的内部实现通常为红黑树,因此它提供了高效的插入、删除和查找操作。主要特点键的唯一性:每个键在 ......
  • C++之stack容器
    stack是C++STL(StandardTemplateLibrary)中的一种容器适配器,用于实现后进先出(LIFO,LastInFirstOut)的数据结构。stack提供了一组基本的操作来管理栈顶元素的插入和移除。stack的底层可以基于不同的容器(如vector、deque或list)实现,默认情况下使用deque。主要特......
  • C++之queue容器
    queue是C++STL(StandardTemplateLibrary)中的一种容器适配器,用于实现先进先出(FIFO,FirstInFirstOut)的数据结构。queue提供了一组基本的操作来管理队列前端和后端的元素。queue的底层可以基于不同的容器(如deque或list)实现,默认情况下使用deque。主要特点先进......
  • 基于JAVA的在线购物平台设计与实现-计算机毕设 附源码 26720
    基于JAVA的在线购物平台设计与实现摘要基于JAVA的在线购物平台设计与实现是一个涉及到软件开发和电子商务的综合课题。在这样的平台上,用户可以浏览商品、将商品加入购物车、进行下单购买等操作。为了实现这一功能,需要考虑到前后端的交互、数据库的设计、安全性和用户体......
  • c++11 --- 左值与右值的使用;
    C++98的C++语法中就有引用的语法,而C++11中新增了的右值引用语法特性,C++11之后我们之前学习的引用就叫做左值引用。无论左值引用还是右值引用,都是给对象取别名(语法层面上)。左值和右值左值是一个表示数据的表达式(如变量名或解引用的指针),一般是有持久状态,存储在内存中,我们......
  • docker实现redis集群
    1.主从模式(Master-Slave)1.1主从复制原理主从复制是redis的一种基本的集群方式,它通过将一个Redis节点(主节点)的数据复制到一个或多个其他Redis节点来实现数据的冗余和备份主节点负责处理客户端的写操作,同时从节点回自动同步主节点的数据。客户端可以从从节点读取数据,实现读取分离......
  • 2、51单片机实现数码管的数值显示
    2.1、实验目的8位共阴数码管显示8位以内的数字2.2、实验环境普中51开发板(stc89c52、74HC245、74HC138、8位共阴数码管)2.3、实验代码#include<reg52.h> #include<intrins.h> typedefunsignedcharu8; typedefunsignedintu16;staticu8digital_buffer[8]......
  • cn.hutool.http.HttpResponse 实现http请求
    前提引入hutool依赖具体实现//发送GET请求publicstaticHttpResponsesendGetRequest(Stringurl,Map<String,List<String>>httpHeaders){HttpResponseresponse=HttpRequest.get(url).header(httpHeaders).ex......