在C++中用虚函数及模版实现委托(支持自定义参数)

#include "stdio.h"

class CObject
{
};

class Event
{
  public:
    unsigned long EventType;
  public:
    Event(unsigned long EventType)
    {
      this->EventType = EventType;
    }
};

class Handler
{
  public:
    virtual void Invoke(CObject* sender, Event* event) = 0;
};

class CSourceEvent : public Event
{
  public:
    char* sourceArg1;
  public:
    CSourceEvent(unsigned long EventType, char* arg1):Event(EventType)
    {
      sourceArg1 = arg1;
    }
};

class CSource : public CObject
{
  public:
    char* name;
    Event* event;
    Handler* handler;
  public:
    CSource(char* name)
    {
      this->name = name;
      this->event = new CSourceEvent(1, "strArg");
      this->handler = 0;
    }
    void fire()
    {
      if(handler) handler->Invoke(this, event);
    }
};

template<class T>
class EventHandler : public Handler
{
  typedef void (T::*funptr)(CObject*, Event* event);
  private:
    T* obj;
    funptr fun;
  public:
    virtual void Invoke(CObject* sender, Event* event)
    {
      (obj->*fun)(sender, event);
    }
  public:
    EventHandler(T* obj, funptr fun)
    {
      this->obj = obj;
      this->fun = fun;
    }
};

class CProcessor
{
  public:
    char* name;
    CSource* source;
  public:
    void OnEvent(CObject* sender, Event* event)
    {
      CSource* source = (CSource*)sender;
      CSourceEvent* sourceEvent = (CSourceEvent*)event;
      printf("Object %s Event %d with Arg %s Processed By %s", source->name, sourceEvent->EventType, sourceEvent->sourceArg1, this->name);
    }
  public:
    CProcessor(char* msg)
    {
      name = msg;
      source = new CSource("source1");
      source->handler = new EventHandler<CProcessor>(this, &CProcessor::OnEvent);
    }
};

int main()
{
  CProcessor* processor = new CProcessor("processor1");
  processor->source->fire();
  return 0;
}

阅读更多

没有更多推荐了,返回首页