Simple State Machine

A simple state machine as works follows:
fig1.png
It contains an initial pseudo state, a normal state and a final state.
The following code is an example implementation of the simple state machine in the diagram above.
#include <iostream>
#include <boost/msm/back/state_machine.hpp>
 
#include <boost/msm/front/state_machine_def.hpp>
#include <boost/msm/front/functor_row.hpp>
 
namespace {
    namespace msm = boost::msm;
    namespace msmf = boost::msm::front;
    namespace mpl = boost::mpl;
 
    // ----- Events
    struct Event1 {};
 
    // ----- State machine
    struct Sm1_:msmf::state_machine_def<Sm1_>
    {
        // States
        struct State1:msmf::state<> 
        {
            // Entry action
            template <class Event,class Fsm>
            void on_entry(Event const&, Fsm&) const {
                std::cout << "State1::on_entry()" << std::endl;
            }
            // Exit action
            template <class Event,class Fsm>
            void on_exit(Event const&, Fsm&) const {
                std::cout << "State1::on_exit()" << std::endl;
            }
        };
        struct End:msmf::terminate_state<> {};
 
        // Set initial state
        typedef State1 initial_state;
 
        // Transition table
        struct transition_table:mpl::vector<
            //          Start   Event   Next    Action      Guard
            msmf::Row < State1, Event1, End,    msmf::none, msmf::none >
        > {};
    };
 
    // Pick a back-end
    typedef msm::back::state_machine<Sm1_> Sm1;
 
    void test()
    {        
        Sm1 sm1;
        sm1.start(); 
        std::cout << "> Send Event1" << std::endl;
        sm1.process_event(Event1());
    }
}
 
int main()
{
    test();
    return 0;
}
 
// Output:
//
// State1::on_entry()
// > Send Event1
// State1::on_exit()

Sm1_ is a state machine definition. In Sm1_, there are 2 states, State1 and End. The initial pseudo state is defined in the code segment containing the initial_state typedef below:

        // Set initial state
        typedef State1 initial_state;

The initial_state typedef means the state machine Sm1_ starts from State1.

Consider the following diagram:
fig2.png
A transition from an initial pseudo state to State1 has an action. To implement this kind of state machine, you need additional codes.

Add a New Comment