c++ - 继承 react

标签 c++ boost boost-statechart

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

像这样(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 的解决方法是在派生类而不是基类中定义它。但是随后,出现了一个奇怪的问题:如果我删除 other react ( react (const OtherEvent& )) 它起作用了。但这当然不是我想要的,我希望能够对多个事件使用react。

最佳答案

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

using BaseState::react;

result react ( const OtherEvent& );

这个可以正常工作。

关于c++ - 继承 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9311916/

相关文章:

c++ - 无法编译我的状态机代码

boost - 为什么我使用 context<State>().method() 违反状态图断言?

c++ - Boost Statechart 中的多个延迟事件

c++ - 为什么这段代码编译时没有提示构造函数?

java - 调用函数时 JNI C++ android 应用程序崩溃

c++ - 如何确定 boost.preprocessor 元组中的元素计数?

c++ - 特定 std::bind 返回的数据类型到底是什么?

c++ - 返回值时调用析构函数

c++ - Windows 7 设备 ContainerID 的替代品

c++ - 将 gsl_ran_hypergeometric_pdf(k, n1, n2, t) 翻译成 boost::math::hypergeometric_distribution