【发布时间】:2012-02-16 13:15:26
【问题描述】:
我想定义一个从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,因此也许我还需要将心跳事件定义为custon_reaction 作为派生类中的列表。但也许这个设计不像这个库的设计者认为的那样,谁能帮我解决这个问题?
编辑
与此同时,我获得了一些额外的知识。 typedef 的解决方法是在派生类而不是基类中定义它。但是随后,出现了一个奇怪的问题:编译器将找不到react (const EvHeartBeat& ) 的方法,尽管它是在基类中定义的,如果我删除 other 反应 (react (const OtherEvent& )) 它可以工作。但这当然不是我想要的,我希望能够对多个事件做出反应。
【问题讨论】:
标签: c++ boost boost-statechart