Header-only flat FSM framework, made as an example to illustrate twitter thread on #cpp #state_machine #software_design.
- Visual Studio 14, 15, 16
- GCC 7, 8
- Clang 5, 6, 7
- Include FFSM header:
#include <ffsm/machine.hpp>
- Define interface class between the state machine and its host (also ok to use the host object itself):
struct Context {
// ...
};
- (Optional, recommended) Typedef
ffsm::Machine
for convenience:
using M = ffsm::Machine<Context>;
- (Optional) Forward declare transition target states:
struct Second;
- Define states inheriting them from
M::State
:
struct First
: M::State
{
virtual void update(Control& control) override {
control.changeTo<Second>();
}
};
struct Second
: M::State
{
virtual void update(Control& control) override {
control.changeTo<First>();
}
};
struct Done : M::State {};
- Declare state machine structure:
using FSM = M::Host<First,
Second,
Done>;
- Write the client code to use your new state machine:
int main() {
- Create context and state machine instances:
Context context;
FSM fsm(context);
- Kick off periodic updates until it's done:
while (!fsm.isActive<Done>())
fsm.update();
return 0;
}