Skip to content

Instantly share code, notes, and snippets.

@eNV25
Last active April 17, 2021 19:09
Show Gist options
  • Save eNV25/c73f0327863bb31dbb0d11569690cff2 to your computer and use it in GitHub Desktop.
Save eNV25/c73f0327863bb31dbb0d11569690cff2 to your computer and use it in GitHub Desktop.
State machine where each state is represented by a function.
#include "state_machine.h"
#include <iostream>
using namespace std;
struct StateFn {
State f;
StateFn(State p) : f(p) {}
operator State(void) { return f; }
};
using State = StateFn (*)(void);
StateFn EOF_state(void) {
cout << "EOF State" << endl;
return nullptr;
}
StateFn other_state(void) {
cout << "Other State" << endl;
return EOF_state;
}
StateFn normal_state(void) {
cout << "Normal State" << endl;
return other_state;
}
int main(void) {
State state;
state = normal_state();
while (state != nullptr) {
state = state();
}
cout << "FIN" << endl;
return 0;
}
#ifndef _STATE_MACHINE_H_
#define _STATE_MACHINE_H_
#pragma once
struct StateFn;
using State = StateFn (*)(void);
StateFn EOF_state(void);
StateFn other_state(void);
StateFn normal_state(void);
#endif // ! _STATE_MACHINE_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment