1

我想定义一个派生自 的基类,statechart::simple_state它具有“预定义”反应,这些反应本身称为虚函数(必须在派生类中实现)。我想要的是,如果某些状态从我的基类派生,它们会自动对某些事件做出反应。

像这样(scboost::statechart):

struct EvHeartBeat : sc::event<EvHeartBeat> {};

template< class MostDerived,
      class Context,
      class InnerInitial = boost::mpl::list<>,
      sc::history_mode historyMode = sc::has_no_history >
class BaseState : public sc::simple_state<
    MostDerived, Context, InnerInitial, historyMode >
{
public:
    typedef sc::custom_reaction<EvHeartBeat> reactions;

    sc::result react (const EvHeartBeat& )
    {
        // maybe check some conditions here ...
        return react_heartbeat();
    }

protected:
    virtual sc::result react_heartbeat() = 0;
};

然后,在派生类中:

struct MyState :
    BaseState<MyState, MyChart>
{

   // there are also other reactions
   typedef sc::custom_reaction<OtherEvent> reactions;

    sc::result react_heartbeat()
    {       
        std::cout << "foo" << std::endl;       
    }

    sc::result react (const OtherEvent&) { /* ... */ }

};

派生类中的typedef将“覆盖”我假设的基类中的那个,所以也许我还需要将custon_reaction心跳事件定义为派生类中的列表。但也许这个设计不像这个图书馆的设计师认为的那样,谁能帮我解决这个问题?

编辑

与此同时,我获得了一些额外的知识。一种解决方法是typedef在派生类而不是基类中定义它。但是,出现了一个奇怪的问题:编译器将找不到一个方法,react (const EvHeartBeat& )尽管它是在基类中定义的,但如果我删除其他反应(react (const OtherEvent& ))它可以工作。但这当然不是我想要的,我希望能够对多个事件做出反应。

4

1 回答 1

0

我也在boost-users毫升上问过这个问题,得到了一个很有帮助的答案。OtherEvent问题是,尽管参数列表不同( vs. EvHeartBeat),但子类中的方法定义遮盖了父类中的定义。解决方案是显式重用超类中的方法:

using BaseState::react;

result react ( const OtherEvent& );

这个工作就像它应该的那样。

于 2012-02-19T14:31:59.153 回答