Skip to content

Instantly share code, notes, and snippets.

@eugeniop
Created November 16, 2014 23:19
Show Gist options
  • Save eugeniop/dda0f4006fb4270658a7 to your computer and use it in GitHub Desktop.
Save eugeniop/dda0f4006fb4270658a7 to your computer and use it in GitHub Desktop.
#ifndef STM_ENGINE
#define STM_ENGINE
namespace Infrastructure
{
enum EventActionResult { EventFailed, EventProcessed };
template<class T>
class State
{
public:
char InputEvent;
State<T> * NextState;
EventActionResult (T::*Action)( char event );
State<T> * ErrorState;
};
#define ANY '*'
template<class T>
class StateMachine
{
private:
State<T> * init;
State<T> * current;
T * target;
public:
StateMachine()
{}
void Init( T * _target, State<T> * initialState )
{
init = current = initialState;
target = _target;
}
void Reset()
{
current = init;
}
void ProcessEvent( char event )
{
for( State<T> * p = this->current; p->NextState != NULL; p++ )
{
if( p->InputEvent == event || p->InputEvent == ANY )
{
if( p->Action != NULL )
{
if( EventFailed == (this->target->*(p->Action))( event ) )
{
if( p->ErrorState != NULL )
{
//Only if there's an errorstate defined. Otherwise, just do nothing
this->current = p->ErrorState;
}
return;
}
}
this->current = p->NextState;
return;
}
}
//Event not found. Do nothing
return;
}
};
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment