A C++17 header-only state machine implementation, leveraging variadic templates for compile-time checking of transitions and event-handling.
struct State {
void OnEnter();
void OnEnter(const ButtonEvent& event); // optional specialization for transition from event
auto Process() -> Maybe<TransitionTo<OtherState>>; // might transition to 'OtherState'
void OnExit();
auto Handle(const Event& event) -> TransitionTo<AnotherState>; // transitions to 'AnotherState'
};
int main() {
StateMachine sm(State{}, OtherState{}, AnotherState{});
sm.Process(); // process currently active state
sm.Handle(Event{}); // currently active state will receive Event
}
States can be very lean, they only have to handle all events.
struct SwitchPressed{};
struct LightOff {
auto Handle(const SwitchPressed &) -> vsm::TransitionTo<LightOn> {
std::cout << "Light is now on\n";
return {};
}
};
struct LightOn {
auto Handle(const SwitchPressed &) -> vsm::TransitionTo<LightOff> {
std::cout << "Light is now off\n";
return {};
}
};
// ...
sm.Handle(SwitchPressed{});
Checkout the examples.
meson setup build
meson test --print-errorlogs -C build
meson setup build
meson compile -C build
./build/examples/traffic_lights
Based on this article by Michael Adamczyk.