worksofcraft
September 30th, 2010, 02:03 AM
OK so I was snuffling through some ancient code of mine and came across my blue print for doing state machines (sample below). IDK anyone else ever program state machines? Is this idea worth pursuing?
#include <stdio.h>
/*
* Base class for making state machines
*/
struct cs_state {
typedef void (cs_state::*state)(void); // current state "method"
state State; // current state of machine
// run the state machine
void operator() (void) {
// NULL state signals the machine terminated
if (State) (this->*State)();
}
bool done() { return State == (state) NULL; }
// constructor sets initial state
cs_state(state InitialState) { State = InitialState; }
// virtual destructor so derivatives can have specialized
// tidy up methods.
virtual ~cs_state() {};
};
// A derived state machine just for demo-porpoises
struct test_state_machine: cs_state {
// has two states
void astate();
void bstate();
// constructor starts it in "a" state
test_state_machine(): cs_state((state) &test_state_machine::astate) {}
~test_state_machine() {
printf("all done... bai!\n");
}
};
void test_state_machine::astate() {
printf("doing astate, press a key\n");
getchar();
State = (state) &test_state_machine::bstate;
}
void test_state_machine::bstate() {
printf("doing bstate, press a key\n");
getchar();
State = NULL;
}
int main() {
test_state_machine Tester;
while (!Tester.done()) Tester(); // call state machine until it finishes
return 0;
}
#include <stdio.h>
/*
* Base class for making state machines
*/
struct cs_state {
typedef void (cs_state::*state)(void); // current state "method"
state State; // current state of machine
// run the state machine
void operator() (void) {
// NULL state signals the machine terminated
if (State) (this->*State)();
}
bool done() { return State == (state) NULL; }
// constructor sets initial state
cs_state(state InitialState) { State = InitialState; }
// virtual destructor so derivatives can have specialized
// tidy up methods.
virtual ~cs_state() {};
};
// A derived state machine just for demo-porpoises
struct test_state_machine: cs_state {
// has two states
void astate();
void bstate();
// constructor starts it in "a" state
test_state_machine(): cs_state((state) &test_state_machine::astate) {}
~test_state_machine() {
printf("all done... bai!\n");
}
};
void test_state_machine::astate() {
printf("doing astate, press a key\n");
getchar();
State = (state) &test_state_machine::bstate;
}
void test_state_machine::bstate() {
printf("doing bstate, press a key\n");
getchar();
State = NULL;
}
int main() {
test_state_machine Tester;
while (!Tester.done()) Tester(); // call state machine until it finishes
return 0;
}