Sim*_*S93 5 c++ pointers function
我不擅长C++(但我熟悉OOP/Java),但我必须为我的C++类创建一个游戏.我想设置一种类似于用ActionScript编写的Flash游戏的游戏引擎.
我写了这两个类,其中Actor是一个基类(可能是抽象的),Player实际上应该实现它.
问题是,我想,以避免功能重复的代码addEventListener和handle并重新申报_handlerMap,因为我要实现数据隐藏和这样的事情.
我想,问题是_eventMap应该包含handler可以改变类Actor::*handler和的值Player::*handler.可能吗?
    class Actor {
    protected:
        typedef void(Actor::*handler)(Event);
        map<int, handler> _handlerMap;
    public:
        virtual void addEventListener(int ID, handler h) {
            _handlerMap.insert(std::make_pair(ID, h));
        };
        virtual void handle(int ID) {
            handler h = _handlerMap[ID];
            Event e;
            if (h)
                (this->*h)(e);
        }
        virtual void onUpdate(Event e) {
            cout << "Actor::onUpdate()" << endl;
        };
    };
class Player : public Actor {
    typedef void(Player::*handler)(Event);
    map<int, handler> _handlerMap;
public:
    void addEventListener(int ID, handler h) {
        _handlerMap.insert(std::make_pair(ID, h));
    };
    void handle(int ID) {
        handler h = _handlerMap[ID];
        Event e;
        if (h)
            (this->*h)(e);
    }
    void onKeydown(Event e) {
        cout << "Player::onKeyDown()" << endl;
    };
};
我希望可以将播放器声明为:
class Player : public Actor {
        typedef void(Player::*handler)(Event);
 public:
        void onWhateverEvent(Event e);
 }
我希望你明白.
你需要这样的东西(未经测试):
class Dispatcher {
  public:
    virtual void dispatchEvent(Event*) = 0;
};
template <class C>
class DispatcherImpl : public Dispatcher
{
    typedef void(C::*handler)(Event* e);
    std::map<int, handler> _handlerMap;
    C* _owner;
  public:
    DispatcherImpl (C* c) : _owner(c) {}
    addEventListener(int ID, handler h) {
        _handlerMap.insert(std::make_pair(ID, h));
    }        
    void dispatchEvent(Event*)
    {
      handler h = handlerMap[e->id];
      if (h) (_owner->*h)(e);
    }
}
现在让每种类型T的演员都拥有一个DispatcherImpl<T>,就可以了。例如,您还可以Player从 继承DispatcherImpl<Player>。