#include #include #include #include #include #include #include #include struct Active {}; struct Stopped : Active {}; struct Running : Active {}; struct EvStartStop {}; struct EvReset {}; template struct process_event_fn { Fsm& m_fsm; Event& m_event; mutable int m_counter; process_event_fn(Fsm& fsm, Event& event) : m_fsm(fsm) , m_event(event) , m_counter(0) {} template void operator()(State*) const { if(m_counter == m_fsm.m_states.which()) { m_fsm.m_states = m_fsm(boost::get(m_fsm.m_states), m_event); throw 0; } ++m_counter; } }; struct Fsm { typedef boost::mpl::vector states; typedef boost::make_variant_over::type state_variant; state_variant m_states; template Fsm(InitialState state) : m_states(state) {} Stopped operator()( Running, EvStartStop ) { std::cout << "Running --> (EvStartStop) --> Stopped\n"; return Stopped(); } Running operator()( Stopped, EvStartStop ) { std::cout << "Stopped --> (EvStartStop) --> Running\n"; return Running(); } Stopped operator()( Active, EvReset ) { std::cout << "Active --> (EvReset) --> Stopped\n"; return Stopped(); } template void process_event(Event event) { using namespace boost::mpl; try { process_event_fn fn(*this, event); boost::mpl::for_each >(boost::ref(fn)); } catch(int) {} } }; int main() { Stopped initial; EvReset evReset; EvStartStop evStartStop; Fsm fsm(initial); fsm.process_event(evStartStop); fsm.process_event(evReset); fsm.process_event(evStartStop); fsm.process_event(evStartStop); fsm.process_event(evReset); }