我想定义一个派生自 的基类,statechart::simple_state
它具有“预定义”反应,这些反应本身称为虚函数(必须在派生类中实现)。我想要的是,如果某些状态从我的基类派生,它们会自动对某些事件做出反应。
像这样(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
在派生类而不是基类中定义它。但是,出现了一个奇怪的问题:编译器将找不到一个方法,react (const EvHeartBeat& )
尽管它是在基类中定义的,但如果我删除其他反应(react (const OtherEvent& )
)它可以工作。但这当然不是我想要的,我希望能够对多个事件做出反应。