在C++中用虚函数及模版实现委托

#include "stdio.h"

class CObject;

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

class CObject
{
  public:
    char* name;
    Handler* handler;
  public:
    CObject(char* name)
    {
      handler = 0;
      this->name = name;
    }
    void fire()
    {
      if(handler) handler->Invoke(this);
    }
};

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

class CProcessor
{
  public:
    char* name;
    CObject* obj;
  public:
    void OnEvent(CObject* sender)
    {
      printf("Object %s Event Processed By %s", sender->name, this->name);
    }
  public:
    CProcessor(char* msg)
    {
      name = msg;
      obj = new CObject("obj1");
      obj->handler = new EventHandler<CProcessor>(this, &CProcessor::OnEvent);
    }
};

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

阅读更多
想对作者说点什么? 我来说一句

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