#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 msm = boost::msm;
namespace mpl = boost::mpl;
using namespace msm::front;
// events
struct coin {};
struct push {};
// front-end: define the FSM structure
struct autodoor_ : public msm::front::state_machine_def<autodoor_>
{
//
struct Locked : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& )
{
std::cout << "entering: Locked" << std::endl;
}
template <class Event,class FSM>
void on_exit(Event const&,FSM& )
{
std::cout << "leaving: Locked" << std::endl;
}
};
//
struct Unlocked : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& )
{
std::cout << "entering: Unlocked" << std::endl;
}
template <class Event,class FSM>
void on_exit(Event const&,FSM& )
{
std::cout << "leaving: Unlocked" << std::endl;
}
};
// the initial state of the player SM. Must be defined
typedef Locked initial_state;
// transition actions
void locked_coin(coin const&)
{
std::cout << "locked::coin\n" << std::endl;
}
void locked_push(push const &)
{
std::cout << "Locked::push\n" << std::endl;
}
void unlocked_coin(coin const &)
{
std::cout << "Unlocked::coin\n" << std::endl;
}
void unlocked_push(push const &)
{
std::cout << "Unlocked::push\n" << std::endl;
}
// Transition table for player
struct transition_table : mpl::vector<
// Start Event Next Action Guard
// +---------+-------------+---------+---------------------+----------------------+
a_row < Locked , coin , Unlocked , &autodoor_::locked_coin >,
a_row < Locked , push , Locked , &autodoor_::locked_push >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Unlocked, coin , Unlocked , &autodoor_::unlocked_coin >,
a_row < Unlocked, push , Locked , &autodoor_::unlocked_push >
// +---------+-------------+---------+---------------------+----------------------+
> {};
};
// Pick a back-end
typedef msm::back::state_machine<autodoor_> autodoor;
//
// Testing utilities.
//
static char const* const state_names[] = { "Locked", "Unlocked"};
void pstate(autodoor const& d)
{
std::cout << " -> " << state_names[d.current_state()[0]] << std::endl;
}
void test()
{
autodoor d;
// needed to start the highest-level SM. This will call on_entry and mark the start of the SM
d.start();
d.process_event(push());
pstate(d);
d.process_event(coin());
pstate(d);
d.process_event(push());
pstate(d);
d.process_event(coin());
pstate(d);
}
int main()
{
test();
return 0;
}
有限自动状态机