我想定义一个从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& )的方法,尽管它是在基类中定义的,如果我删除了其他的reaction (react (const OtherEvent& )),它就能工作。但这当然不是我想要的,我希望能够对多个事件做出反应。
发布于 2012-02-19 14:31:59
我也在boost-users ml上问了这个问题,得到了一个很有帮助的答案。问题是,子类中的方法定义阴影了父类中的定义,尽管参数列表不同(OtherEvent与EvHeartBeat)。解决方案是显式重用超类中的方法:
using BaseState::react;
result react ( const OtherEvent& );这个应该用的。
https://stackoverflow.com/questions/9311916
复制相似问题