【问题标题】:Boost::msm How to initialize state_machine_def and msm::front::state with non-default constructorBoost::msm 如何使用非默认构造函数初始化 state_machine_def 和 msm::front::state
【发布时间】:2017-07-19 11:01:57
【问题描述】:

我的状态机是这样的:

class FsmDef : public boost::msm::front::state_machine_def<FsmDef> {
private:
    Args args;
    using State = boost::msm::front::state<>;
public:
    FsmDef(Args args) : args{args}
    {}


    struct InitState {};
    struct State1 {
        Args1 args1;
        State1(Args1 args1) : args1(args1)
         {}
    };

    struct transition_table : boost::mpl::vector<
        boost::msm::front::Row<Init, boost::msm::front::none, State1>
    > { };

    using initial_state = InitState;
};

using Fsm = boost::msm::back::state_machine<FsmDef>;

Fsm fsm;

如何构造fsm 并为FsmDef 初始化私有数据。 State1 也一样。

【问题讨论】:

    标签: c++ state-machine boost-msm


    【解决方案1】:

    FsmDef 可以是非默认可构造的。但是State1 需要默认构造。

    这是一种将参数传递给FsmDef的方法。

    #include <iostream>
    #include <boost/msm/back/state_machine.hpp>
    
    #include <boost/msm/front/state_machine_def.hpp>
    #include <boost/msm/front/functor_row.hpp>
    
    struct Args {
        int val;
    };
    
    class FsmDef : public boost::msm::front::state_machine_def<FsmDef> {
    private:
        Args args_;
        using State = boost::msm::front::state<>;
    public:
        FsmDef(Args args) : args_{args}
        {
            std::cout << args_.val << std::endl;
        }
    
    
        struct InitState : boost::msm::front::state<> {};
        struct State1 : boost::msm::front::state<> {
        // states must be default constructible
        //    Args1 args1;
        //    State1(Args1 args1) : args1(args1)
        //    {}
        };
    
        struct transition_table : boost::mpl::vector<
            boost::msm::front::Row<InitState, boost::msm::front::none, State1>
        > { };
    
        using initial_state = InitState;
    };
    
    using Fsm = boost::msm::back::state_machine<FsmDef>;
    
    int main() {
        Args a {42};
        Fsm fsm(a);
    }
    

    运行演示https://wandbox.org/permlink/ZhhblHFKYWd3ieDK

    Fsmboost::msm::back::state_machine&lt;FsmDef&gt; 具有与FsmDef 具有相同参数的构造函数。 AFAIK,它没有明确记录。

    这是定义构造函数的代码。

    https://github.com/boostorg/msm/blob/boost-1.64.0/include/boost/msm/back/state_machine.hpp#L1625

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 1970-01-01
      • 2011-06-17
      • 2020-01-18
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      相关资源
      最近更新 更多