我有一个状态机,如果我进入一个特定的状态,有时我需要定期转换到另一个状态,而其他时候我需要返回到以前的状态。
例如,具有状态 ABC,假设转移 S 将状态 A 移动到 C 并从 B 转移到 C。我需要当 S 发生在状态 A 时转移 T 将 C 转移到 A,当它发生在状态 B 时转移 C 到 B。
在下面的代码中,转换 S 发生在状态 B 中,因此我希望转换 T 返回到状态 B(而目前,它返回到状态 A)。
#include <boost/mpl/list.hpp>
#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/event.hpp>
#include <boost/statechart/transition.hpp>
// states
struct A;
struct B;
struct C;
struct D;
// events
struct S : boost::statechart::event<S> {};
struct T : boost::statechart::event<T> {};
struct U : boost::statechart::event<U> {};
// fsm
struct FSM : boost::statechart::state_machine<FSM, B> {};
// fully defined states/transitions
struct A : boost::statechart::simple_state<A, FSM> {
typedef boost::statechart::transition<S, C> reactions;
A() { std::cout << "entered A" << std::endl; }
};
struct B : boost::statechart::simple_state<B, FSM> {
typedef boost::statechart::transition<S, C> reactions;
B() { std::cout << "entered B" << std::endl; }
};
struct C : boost::statechart::simple_state<C, FSM> {
typedef boost::mpl::list<
boost::statechart::transition<T, A>,
boost::statechart::transition<T, B>,
boost::statechart::transition<U, D> > reactions;
C() { std::cout << "entered C" << std::endl; }
};
struct D : boost::statechart::simple_state<D, FSM> {
D() { std::cout << "entered D" << std::endl; }
};
int main() {
FSM fsm;
fsm.initiate();
fsm.process_event(S());
fsm.process_event(T());
fsm.process_event(S());
fsm.process_event(U());
return 0;
}
上面的代码返回:
entered B
entered C
entered A
entered C
entered D
而我想看到:
entered B
entered C
entered B
entered C
entered D
使用 Boost::Statechart 是否有任何干净的方法可以做到这一点?