【问题标题】:Inherit reactions继承反应
【发布时间】:2012-02-16 13:15:26
【问题描述】:

我想定义一个从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,因此也许我还需要将心跳事件定义为custon_reaction 作为派生类中的列表。但也许这个设计不像这个库的设计者认为的那样,谁能帮我解决这个问题?

编辑

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

【问题讨论】:

    标签: c++ boost boost-statechart


    【解决方案1】:

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

    using BaseState::react;
    
    result react ( const OtherEvent& );
    

    这个工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-18
      • 2019-10-27
      • 1970-01-01
      • 2020-09-13
      • 2011-03-19
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      相关资源
      最近更新 更多