用 C++ 实现 C# 中的 委托/事件 (2-delegate event functor)

用C++模拟C#事件机制     C#中的事件机制可以很方便的实现设计模式中的Observer模式,C#提供了delegate 和 event 来实现这种机制,实际上只要delagate就可以实现event效果,event语法完全没必要,因为delegate是多播的。本文提供了一个C++版本的实现,与C#原生的事件机制相比,只有一点不同,我实现的delegate是单播的(为了避免delegate 和 event 功能重复的 阅读详情

前两天看程序员杂志
看到关于 C# 中的委托/事件
觉得用起来好像是挺方便的
本人热衷于 C++
想想用 C++ 来模拟似乎也可以
于是就有了下面的代码...
(VC6 不支持偏特化 本人工作环境就是 VC6 痛啊~~~)

没有返回值的函数用 delegate
否则就用 delegate_rt
functor 也一样 functorN/functorN_rt
delegate 的模板参数可以是函数指针(非成员函数)
也可以是 functor
还可以是 delegate
functor 可用 make_functor/make_functor_rt 来生成
要是有偏特化 就可以去掉讨厌的 _rt 了 :(

关于委托 boost里有现成的
不过可能 VC6 里用不了

这些代码旨在个人研究
如果大家发现其中问题 希望能指出

//filename: delegate.h
#ifndef _DELEGATE_H_
#define _DELEGATE_H_

#include <vector>
#include <algorithm>
#include "delegate_rt.h"

template <typename T>
class delegate
{
protected:
  std::vector<T> funcs;
public:
  typedef T FunctorType;

  delegate() {}
  explicit delegate(T Func)
  {
    if (!(Func == NULL)) funcs.push_back(Func);
  }
  delegate(const delegate& rhs) : funcs(rhs.funcs) {}

  void operator ()() const
  {
    typename std::vector<T>::const_iterator i = funcs.begin();
    for (; i != funcs.end(); ++i)
    {
      (*i)();
    }
  }
 template <typename P1>
  void operator ()(P1 p1) const
  {
    typename std::vector<T>::const_iterator i = funcs.begin();
    for (; i != funcs.end(); ++i)
    {
      (*i)(p1);
    }
  }
 template <typename P1, typename P2>
  void operator ()(P1 p1, P2 p2) const
  {
    typename std::vector<T>::const_iterator i = funcs.begin();
    for (; i != funcs.end(); ++i)
    {
      (*i)(p1, p2);
    }
  }
  bool operator ==(const delegate& rhs) const
  {
    return funcs == rhs.funcs;
  }
  bool operator ==(const void* rhs) const
  {
    if (funcs.size())
      return &funcs == rhs;
    return NULL == rhs;
  }

  delegate& operator =(const delegate& rhs)
  {
    funcs = rhs.funcs;
    return *this;
  }
  delegate& operator +=(const delegate& rhs)
  {
    if (this == &rhs)
      return *this;
    typename std::vector<T>::const_iterator j, i = rhs.funcs.begin();
    for (; i != rhs.funcs.end(); ++i)
    {
      j = std::find(funcs.begin(), funcs.end(), *i);
      if (j == funcs.end())
        funcs.push_back(*i);
    }
    return *this;
  }
  delegate& operator -=(const delegate& rhs)
  {
    if (this == &rhs)
    {
      funcs.clear();
      return *this;
    }
    typename std::vector<T>::iterator j;
    typename std::vector<T>::const_iterator i = rhs.funcs.begin();
    for (; i != rhs.funcs.end(); ++i)
    {
      j = std::find(funcs.begin(), funcs.end(), *i);
      if (j != funcs.end())
        funcs.erase(j);
    }
    return *this;
  }
  delegate operator +(const delegate& rhs) const
  {
    return delegate(*this) += rhs;
  }
  delegate operator -(const delegate& rhs) const
  {
    return delegate(*this) -= rhs;
  }

  delegate& operator =(T rhs)
  {
    funcs.clear();
    if (!(rhs == NULL))
      funcs.push_back(rhs);
    return *this;
  }
  delegate& operator +=(T rhs)
  {
    if (rhs == NULL)
      return *this;
    typename std::vector<T>::const_iterator j = 
      std::find(funcs.begin(), funcs.end(), rhs);
    if (j == funcs.end())
      funcs.push_back(rhs);
    return *this;
  }
  delegate& operator -=(T rhs)
  {
    if (rhs == NULL)
      return *this;
    typename std::vector<T>::iterator j = 
      std::find(funcs.begin(), funcs.end(), rhs);
    if (j != funcs.end())
      funcs.erase(j);
    return *this;
  }
  delegate operator +(T rhs) const
  {
    return delegate(*this) += rhs;
  }
  delegate operator -(T rhs) const
  {
    return delegate(*this) -= rhs;
  }
  friend delegate operator +(T lhs, const delegate& rhs)
  {
    return rhs + lhs;
  }
};

#endif // #ifndef _DELEGATE_H_
//filename: delegate_rt.h
#ifndef _DELEGATE_RT_H_
#define _DELEGATE_RT_H_

#include <vector>
#include <algorithm>
#include <stdexcept>

template <typename R, typename T>
class delegate_rt
{
protected:
  std::vector<T> funcs;
public:
  typedef T FunctorType;
  typedef R ReturnType;

  delegate_rt() {}
  explicit delegate_rt(T Func)
  {
    if (!(Func == NULL)) funcs.push_back(Func);
  }
  delegate_rt(const delegate_rt& rhs) : funcs(rhs.funcs) {}

  ReturnType operator ()() const
  {
    if (funcs.size() != 1)
      throw std::runtime_error("non-multicast delegate: method error!");
    return funcs.front()();
  }
 template <typename P1>
  ReturnType operator ()(P1 p1) const
  {
    if (funcs.size() != 1)
      throw std::runtime_error("non-multicast delegate: method error!");
    return funcs.front()(p1);
  }
 template <typename P1, typename P2>
  ReturnType operator ()(P1 p1, P2 p2) const
  {
    if (funcs.size() != 1)
      throw std::runtime_error("non-multicast delegate: method error!");
    return funcs.front()(p1, p2);
  }
  bool operator ==(const delegate_rt& rhs) const
  {
    return funcs == rhs.funcs;
  }
  bool operator ==(const void* rhs) const
  {
    if (funcs.size())
      return &funcs == rhs;
    return NULL == rhs;
  }

  delegate_rt& operator =(const delegate_rt& rhs)
  {
    funcs = rhs.funcs;
    return *this;
  }
  delegate_rt& operator +=(const delegate_rt& rhs)
  {
    if (this == &rhs)
      return *this;
    typename std::vector<T>::const_iterator j, i = rhs.funcs.begin();
    for (; i != rhs.funcs.end(); ++i)
    {
      j = std::find(funcs.begin(), funcs.end(), *i);
      if (j == funcs.end())
        funcs.push_back(*i);
    }
    return *this;
  }
  delegate_rt& operator -=(const delegate_rt& rhs)
  {
    if (this == &rhs)
    {
      funcs.clear();
      return *this;
    }
    typename std::vector<T>::iterator j;
    typename std::vector<T>::const_iterator i = rhs.funcs.begin();
    for (; i != rhs.funcs.end(); ++i)
    {
      j = std::find(funcs.begin(), funcs.end(), *i);
      if (j != funcs.end())
        funcs.erase(j);
    }
    return *this;
  }
  delegate_rt operator +(const delegate_rt& rhs) const
  {
    return delegate_rt(*this) += rhs;
  }
  delegate_rt operator -(const delegate_rt& rhs) const
  {
    return delegate_rt(*this) -= rhs;
  }

  delegate_rt& operator =(T rhs)
  {
    funcs.clear();
    if (!(rhs == NULL))
      funcs.push_back(rhs);
    return *this;
  }
  delegate_rt& operator +=(T rhs)
  {
    if (rhs == NULL)
      return *this;
    typename std::vector<T>::const_iterator j = 
      std::find(funcs.begin(), funcs.end(), rhs);
    if (j == funcs.end())
      funcs.push_back(rhs);
    return *this;
  }
  delegate_rt& operator -=(T rhs)
  {
    if (rhs == NULL)
      return *this;
    typename std::vector<T>::iterator j = 
      std::find(funcs.begin(), funcs.end(), rhs);
    if (j != funcs.end())
      funcs.erase(j);
    return *this;
  }
  delegate_rt operator +(T rhs) const
  {
    return delegate_rt(*this) += rhs;
  }
  delegate_rt operator -(T rhs) const
  {
    return delegate_rt(*this) -= rhs;
  }
  friend delegate_rt operator +(T lhs, const delegate_rt& rhs)
  {
    return rhs + lhs;
  }
};

#endif // #ifndef _DELEGATE_RT_H_
 
 
//filename: event.h
#ifndef _EVENT_H_
#define _EVENT_H_

typedef void* object;

class EventArgs
{
public:
  bool cancel;
  EventArgs() : cancel(false) {}
};

template <typename T>
class event
{
  T handlers;
public:
  void operator +=(const T& rhs)
  {
    handlers += rhs;
  }
  void operator -=(const T& rhs)
  {
    handlers -= rhs;
  }
  void operator()() const
  {
    handlers(NULL, EventArgs());
  }
   template <typename P1>
  void operator()(P1 p1) const
  {
    handlers(p1, EventArgs());
  }
   template <typename P1, typename P2>
  void operator()(P1 p1, P2 p2) const
  {
    handlers(p1, p2);
  }
};

#endif // #ifndef _EVENT_H_
 
//filename: functor.h
#ifndef _FUNCTOR_H_
#define _FUNCTOR_H_

template<typename T, typename T1, typename T2, typename T3>
class functor_base
{
public:
  typedef T deleobject;
  typedef T1 func_pt;
  typedef T2 mem_func_pt;
  typedef T3 cmem_func_pt;
  union
  {
    func_pt m_pf;
    mem_func_pt m_pmf;
    cmem_func_pt m_pcmf;
  };
  union
  {
    deleobject *m_pObject;
    const deleobject *m_pcObject;
  };
  functor_base() : m_pf(NULL), m_pObject(NULL) {}
  functor_base(func_pt pf) : 
    m_pf(pf), m_pObject(NULL) {}
  functor_base(const deleobject *pObject, mem_func_pt pf) : 
    m_pmf(pf), m_pcObject(pObject) {}
  functor_base(const deleobject *pObject, cmem_func_pt pf) : 
    m_pcmf(pf), m_pcObject(pObject) {}
  bool operator !=(const functor_base& rhs) const { return !(*this == rhs); }
  bool operator ==(const functor_base& rhs) const
  {
    if (m_pObject == NULL)
      return rhs.m_pObject == NULL && m_pf == rhs.m_pf;
    return m_pObject == rhs.m_pObject && m_pmf == rhs.m_pmf;
  }
  bool operator ==(const void* rhs) const
  {
    return m_pObject == NULL ? m_pf == rhs : *(const void**)&m_pmf == rhs;
  }
  functor_base& operator =(const functor_base& rhs)
  {
    if (&rhs == this)
      return *this;
    m_pObject = rhs.m_pObject;
    if (m_pObject == NULL)
      m_pf = rhs.m_pf;
    else
      m_pmf = rhs.m_pmf;
    return *this;
  }
};

#include "functor0.h"
#include "functor1.h"
#include "functor2.h"
#include "functor0_rt.h"
#include "functor1_rt.h"
#include "functor2_rt.h"

#endif // #ifndef _FUNCTOR_H_
在C++中实现C#的委托 通过研究,这两天写了一个C++ 的Delegate。关键调用部分使用汇编写成,效率是可以保证的。同时支持32位和64位系统。 支持“+=”操作符构造委托链。 但是,目前不支持将“虚函数”作为委托的目标函数。普通成员函数和静态成员函数都可以的。 目前也不支持异步的委托。 基本用法如下: (其实我是重写了这文章中的例子:http://blog.csdn.net/cjl5678 阅读详情

相关推荐

C++实现委托与事件代理

C++实现委托与事件代理        写在前面的话:这里主要会涉及到vector、reinterpret_cast类型转换运算符、指针成员、事件函数、代理模式,模版编程……等知识,最好有一定了解才往下看,最好就是研究过Don Clugston写的FastDelegate委托,跟C#的委托很相似,当然,大神们写的代码都是很难懂的,没有一定基础和知识,研究起来会非常吃力,我就是研究了两天两夜,才研

zx504287的专栏 2130

C++模拟Event和Delegate

C++作为一门像瑞士军刀一样的编程

MemoryFadesAway的专栏 1099

事件触发最简单例子event delegate

事件触发最简单例子event delegate

[UE4] C++实现Delegate Event实例(例子、example、sample)

原文作者:@玄冬Wong 转载请注明出处:http://aigo.iteye.com/blog/2301010   虽然官方doc上说Event的Binding方式跟Multi-Cast用法完全一样,Multi-Cast论坛上也有很多例子,但是实际是不一样。。而且论坛上找不到相关例子。后来看了下runtime/core的源码,Event的binging方式如下(附上完整步骤):

过期的码农 1672

保姆级教程:用MATLAB复现格拉斯哥大学FMCW雷达数据集多普勒谱(附完整代码与避坑指南)

本文提供了一份详细的MATLAB教程,指导如何复现格拉斯哥大学FMCW雷达数据集的多普勒谱分析。从环境准备、数据获取到距离压缩、MTI滤波、时频分析(STFT)以及结果后处理,涵盖了完整流程,并附有优化代码和避坑指南,特别适合雷达信号处理研究者和工程师。

weixin_28720767的博客 123

【护网行动-红蓝攻防】第一章-红蓝对抗基础 认识红蓝紫

军事上的演练,是除了实战以外最能检验军队战斗力的一种考核方式,他可以模拟面对外部势力的攻击时候,如何更好的去维护国家和主权的安全。同样的,在网络上面,真实环境下的网络攻防演练也是检验一个单位,企业网络防御能力,发现潜在危险最好的方法。1.政策要求2安全威胁驱动当前,我国关键信息基础设施面临的网络安全形势严峻复杂,网站平台大规模数据泄露事件频发,生产业务系统安全隐患突出,甚至有的系统长期被控面对高级持续性的网络攻击,防护能力十分欠缺。目前,我国面临的网络安全威胁主要有以下几点。

wxh的博客 1586

用C++实现C#中的委托和事件

 C#中的测试代码:using System;namespace testEventApp{ public delegate void ClassSender_Event_Handler(object sender, string strEventArg); /// /// ClassReceiver 的摘要说明。 /// class ClassR

双脚踏实地 2028

华为eNSP实战:手把手教你配置DHCP全局地址池(含AP固定IP分配)

本文通过华为eNSP模拟器,详细演示了如何配置DHCP全局地址池,为不同业务VLAN动态分配IP地址,并重点讲解了如何通过MAC地址绑定为接入点(AP)分配固定IP。文章涵盖了从拓扑设计、基础网络搭建到地址池精细配置、验证测试及常见故障排查的全流程,是网络工程师掌握企业级DHCP部署与AP管理的实用指南。

weixin_29235923的博客 606

c++实现委托

熟悉C#的同学可能会接触到委托,用起来也非常方便和顺手,委托就像一个类型一样,更够进行赋值,绑定多个函数事件,委托被调用后,所有被绑定的函数会依次被调用。但是c++语法层面不支持委托操作,学过c语言的同学应该知道,c/c++中的函数名其实是指针,那么只需要对其进行一些简单的封装便可以实现基本的委托功能。 但当中有一个难点,如何支持不同参数类型和不同返回值类型的函数呢? 这里楼主采用了可变参数的模...

qq_39347851的博客 480

汽车级智能栅极驱动器深度解析 | 连载03:功能框图与工作模式详解

在前两期连载中,我们分析了DRV871x-Q1的产品架构、引脚配置和电气特性。本期我们将深入探讨DRV871x-Q1的功能框图和工作模式,这是理解芯片内部工作机制的关键。通过分析功能框图,我们能够清晰地了解各功能模块之间的关系和信号流向;通过工作模式分析,我们能够掌握芯片在不同应用场景下的配置方法。这些知识对于系统设计和故障排查都至关重要。

VehSwHwDeveloper的博客 1119

某瓜数据app 获取达人直播商品信息接口 Sign

某瓜数据app 获取达人直播商品列表接口 Sign

自成背后的博客 6048

在C++中模拟委托事件的方法(四)

三、静态函数方式实现多对象事件接收 对应的例子工程名MultiObjectEvent 在静态函数模拟事件方法中,如果读者细心的话,会发现类CNotifyClass只包含一个指定对象的成员变量m_pEventParameter,在使用RegisterEvent方法注册接收事件的函数时如果不接收某些事件,就把相应的函数参数设为NULL,但是接收事件的对象参数只能是一个,这样就不能有多个类CRecv

gogogo的专栏 2639

4.Simulink基础建模操作——加减乘除运算

加减乘除运算

FPGA/MATLAB学习教程/源码/项目合作开发 9568

编程语言难度排名:从Python到Lisp,10种语言学习成本全解析

编程语言是开发者与计算机沟通的核心工具,其设计哲学和语法特性决定了学习曲线和应用场景。从原理上看,语言的难度通常由语法复杂度、概念抽象层级、生态成熟度等维度综合决定。在技术价值层面,易学的语言能快速实现想法、降低入门门槛,而复杂的语言则提供了更强的控制力、性能或独特的编程范式,适用于系统级开发、高性能计算或学术研究。常见的应用场景包括Web开发、数据分析、移动应用、操作系统、嵌入式系统等。本文基于‘编程语言难度测量仪’思维模型,对Python、JavaScript、Java、Go、C#、C++、Rust、H

weixin_33806914的博客 413

【LIN总线测试】——LIN主节点数据链路层测试

LIN总线是基于UART/SCI(通用异步收发器/串行接口)的低成本串行通讯协议。其目标定位于车身网络模块节点间的低端通信,主要用于智能传感器和执行器的串行通信,而这正是CAN总线的带宽和功能所不要求的部分。本章节主要介绍LIN主节点数据链路层如何测试?

测试领域技术分享 2620

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

C++中的事件分发器与委托

#include "CoreLib/Events.hpp" class EventTest { public: int cb_index; Action<int> e; void lambda_inst(int c) { std::cout << "lambda_inst callback" << std::endl; } void bind_inst(int c) { std::cout &l

SharenFish的博客 1041

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

事件和委托的C++实现

 C#中存在着事件和委托的用法,广泛的应用在Form的编码中。很方便,MFC就不是这样的机制。 本文将描述委托的一种实现方法。Boost中也有委托的实现,各位也可以去学习。 还是从代码开始学习

郭大鸣 的技术专栏 653

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

c++ 实现delegate(支持普通函数与成员函数)

最近开始写了一些c#的东西,有个delegate的东西蛮有意思。 比如如下C#代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpConsole { public...

HLW0522的博客 1805

杂货边角(9):C++实现事件委托机制

在设计模式中,根据耦合紧密度可以得到排序为:继承 > 依赖 > 组合/聚合 > 委托。其实个人感觉,事件委托机制说白了就是一个函数指针数组,通过注册绑定的函数,然后在特定的事件发生后触发遍历执行所有注册的函数,机制其实和C++运行库glibc中crtbegin.o和crtend.o收集当前程序中所有全局对象的初始化函数和析构函数,用以执行遍历操作一致。所以归根结底,事件委托机制的关键便是函数指针注册

墨篙和小奶猫 650

C#委托(delegate、Action、Func、predicate)和事件

一、前言 刚开始工作的时候,觉得委托和事件有些神秘,而当你理解他们之后,也觉得好像没有想象中的那么难。在项目中运用委托和事件,你会发现他非常棒,这篇博文算是自己对委托和事件的一次梳理和总结。 二、委托 C#中的委托,相当于C++中的指针函数,但委托是面向对象的,是安全的,是一个特殊的类,当然他也是引用类型,委托传递的是对方法的引用。 2.1、delegate 声明委托就必须使用...

CL10011314155的博客 504

C++中实现委托(Delegate)

<br />http://blog.huang-wei.com/2010/08/09/c%E4%B8%AD%E5%AE%9E%E7%8E%B0%E5%A7%94%E6%89%98%EF%BC%88delegate%EF%BC%89/<br /> C++中实现委托(Delegate)<br />公司的项目里有用到Don Clugston的FastDelegate,当时只知道是类似boost::function的东西,UI上当watcher用的比较多,所以也没去关注。今天想写个事件触发器时,突然想起这茬子,看来

huangwei.pro 1751

C++的事件

 C#的事件和Windows窗口编程中提到的“事件”、“消息”、“事件驱动”等在概念上是很类似的。我们在一个窗口上移动鼠标指针,系统就会产生WM_MOUSEMOVE消息(在vb中就是激发mousemove事件),只要我们告诉系统一个函数指针,系统就会通过这个回调函数通知我们,这是Windows窗口编程中的“事件”。C#中的事件的外延更广,任何一个对象都可以拥有事件,客户可以“定制”该对象的事件,当

884

C++事件(Event)机制的实现

C++事件(Event)机制的实现 2007-10-01 14:13 752人阅读 评论(0) 收藏 举报 用C++实现事件机制我以前写过一个小例子,但不是很完善,比如Event只能接受全局函数作为handler,类成员方法不可以,还有一个Event只能添加一个handler等……最近我的一个程序刚好要用到Event机制,所以我就抽了些时间,重新实现了一下。这个版本应该说是比

junecau的专栏 7018

对delegate、Func、Action、event、UnityEvent、UnityAction委托一族的总结

对委托相关知识的总结,参考了一些博客再加上了自己的理解。 delegate、Func、Action、event、UnityEvent、UnityAction 委托 一种可用于封装命名或者匿名方法的引用类型。 它的存在说明变量不仅能存储值,对象的引用,还能存方法。只不过声明时前面加个delegate。与函数指针不是同个概念。 类似于 C++ 中的函数指针,而且是类型安全和可靠的。 可用于简化...

KeeeepGO的博客 3850

C++中的delegate

《以boost::function和boost:bind取代虚函数》,原文链接:http://blog.csdn.net/solstice/article/details/3066268 ,很多年前的一篇blog,感觉收获颇丰。 第一个问题,虚函数是否可以被取代?--完全可以。 虚函数一般是用来实现多态,或者说是接口与实现分析。可以直接拿作者的例子来举例:   上面可以说是对象装配的过

胜利者的经验并不复杂,那就是寻找人生的关键点,并在关键时刻竭尽全力 4918
下一篇: 用 C++ 实现 C# 中的 委托/事件 (1-delegateEMU.cpp)
coolcch
博客等级 码龄26年 0粉丝 8原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址