我想定义一个基类,它派生自 statechart::simple_state
,它具有“预定义” react ,这些 react 本身称为虚函数(必须在派生类中实现)。我想要的是,如果某些状态派生 self 的基类,则某些状态会自动对某些事件使用react。
像这样(sc
是 boost::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 上问过这个问题,得到的答案很有帮助。问题是,尽管参数列表不同(OtherEvent
与 EvHeartBeat
),但子类中的方法定义掩盖了父类中的定义。解决方案是显式地重用父类(super class)中的方法:
using BaseState::react;
result react ( const OtherEvent& );
这个可以正常工作。
关于c++ - 继承 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9311916/