boost-ext / sml

C++14 State Machine library
https://boost-ext.github.io/sml
Boost Software License 1.0
1.1k stars 173 forks source link

How to get current states in action/entry? #476

Open Micbetter opened 2 years ago

Micbetter commented 2 years ago

Question

I want to get the current states in action. I found some solutions in [#94] and tried to pass sm to my action function. But it didn't work for me.

My code

#include <iostream>
#include <cassert>
#include <boost/sml.hpp>

namespace sml = boost::sml;

struct e1 {};
struct e2 {};

class s1;
class s2;
class s3;
class s4;

auto action1 = [](const auto& e, auto& sm) {
    sm.visit_current_states([](auto state) {
        cout << "Current State:" << state.c_str() << endl;
        }};

struct table {
    auto operator()() const noexcept {
        using namespace sml;
        return make_transition_table(
            *state<s1> + event<e1> / action1 = state<s3>
            , state<s1> + event<e2> = state<s2>
            , state<s3> + event<e2> = state<s4>
        );
    }
};

int main() {
    using namespace sml;
    sm<table> sm;

    sm.process_event(e1{});
    assert(sm.is(state<s4>));
}

Error

Some compile errors occured.

Specifications

MountainLogic commented 6 months ago

Not sure this is exactly what you are looking for:

static void on_entry_action(std::string i) {std::cout << "on_entry_action " << i << std::endl;} 
...
, "Init"_s            + sml::on_entry<_> / [] { on_entry_action("Init");}
, state<s3>  + sml::on_entry<_> / [] { (  std::cout << "entering " << std::string{sml::aux::string< s3>{}.c_str()}   << std::endl ) ;}  
, state<S4>  + sml::on_exit<_>  / [] { on_exit_action( std::string{sml::aux::string< S4>{}.c_str()} );  }