Created
October 10, 2012 16:38
-
-
Save tkemp/3866757 to your computer and use it in GitHub Desktop.
Simple C++ State machine implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The transition table itself | |
SMTransition MyClass::transitionTable[] = { | |
{ SMStateStart, SMEventAlpha, &MyClass::transToOne }, | |
{ SMStateStart, SMEventBeta, &MyClass::transToTwo }, | |
... | |
{ SMStateAny, SMEventAnyEvent, &MyClass::transDoNothing } | |
}; | |
// Macro to give us the number of transitions in the table | |
#define TR_COUNT (sizeof(transitionTable) / sizeof(*transitionTable)) | |
void MyClass::process() { | |
if (nextEvent != SMNoEvent) { | |
for (int i = 0; i < TRANSITION_COUNT; i++) { | |
if (transitionTable[i].state == curState || transitionTable[i].state == SMAnyState) { | |
if (transitionTable[i].event == nextEvent || transitionTable[i].event == SMAnyEvent) { | |
curState = (this->*transitionTable[i].tFunc)(); | |
break; | |
} | |
} | |
} | |
} | |
} | |
// recEventB and on are basically the same, so just showing A here | |
void MyClass::recEventA() { | |
// Validate or do some internal processing if we really need to but mainly just... | |
nextEvent = SMEventAlpha; | |
} | |
// Transition functions | |
SMState MyClass::transToStart() { | |
// Do our work to get into the Start state. Initialize things, perhaps, or clear flags. | |
nextEvent = SMEventNoEvent; | |
return SMStateStart; | |
} | |
SMState MyClass::transToOne() { | |
// Exactly as above: do whatever we need to do internally to be in the One state. | |
nextEvent = SMEventNoEvent; | |
return SMStateOne; | |
} | |
SMState MyClass::transDoNothing() { | |
nextEvent = SMEventNoEvent; | |
return curState; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment