boost :: msm - 一种获取状态的字符串表示(即.getName)的方法?

时间:2013-01-04 23:38:49

标签: c++ boost-msm

我正在尝试使用boost :: msm库在我的代码中创建状态机。有没有人知道获取状态的字符串名称(而不是int id)的方法?我试图将其用于日志记录/调试目的。例如在no_transition函数中,我得到了状态id,但我正在尝试获取一个名称,因此它更容易阅读:

template <class Event ,class Fsm>
    void no_transition(Event const& e, Fsm& fsm, int stateId)
    {
        //This is what I'm trying: 
        auto state = fsm.get_state_by_id(stateId); //This returns a boost::msm::front::default_base_state. Anything I can override in there to set a name?
        const char* stateName = state->getStateName(); //I want to do something like this since I can do e.getEventId()

        print("FSM rejected the event %s as there is no transition from current state %s (%d)\n", e.getEventId(), stateName, stateId);
    }

以下是我定义事件和状态的方式: 状态:

struct Idle : front::state<> {
 static const char* const getStateName() {
        return "Idle";
    }
};

事件:

struct SampleEvent {
    SampleEvent() {}
    static const char* const getEventId() {
        return "SampleEvent";
    }
};

任何想法都会很棒。谢谢!

2 个答案:

答案 0 :(得分:4)

  1. 最佳选择:使用访客。
    查看http://www.boost.org/doc/libs/1_53_0/libs/msm/doc/HTML/examples/SM-2Arg.cpp

  2. 使用no_transition的最后一个参数(state_id),您可以从数组中检索名称:

    static char const * const state_names [] = {“State1”,“State2”,...};
    打印(state_names [STATE_ID]);

  3. 请注意,提供状态ID仅用于调试目的。 ID在编译时生成,并取决于转换表中条目的顺序

    对MSM文档的引用:

答案 1 :(得分:3)

您可以使用以下代码获得所需的效果:

 #include <boost/msm/back/tools.hpp>
 #include <boost/msm/back/metafunctions.hpp>
 #include <boost/mpl/for_each.hpp>
  .......
  .......
    template <class Event ,class Fsm>
    void no_transition(Event const& e, Fsm& fsm, int stateId){
        typedef typename boost::msm::back::recursive_get_transition_table<FSM>::type recursive_stt;
        typedef typename boost::msm::back::generate_state_set<recursive_stt>::type all_states;
        std::string stateName;
        boost::mpl::for_each<all_states,boost::msm::wrap<boost::mpl::placeholders::_1> >(boost::msm::back::get_state_name<recursive_stt>(stateName, state));
        std::cout << "No transition from state: " << stateName << std::endl;}