Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
C++ state machine prototype
//Title of this code #include <iostream> #include <array> #include <memory> using namespace std; class StateMachineEvent { private: mutable bool bDismiss; public: StateMachineEvent() : bDismiss(false) { } bool isDismissed() const { return bDismiss; } void dismiss() const { bDismiss = true; } }; class StateMachineEventHandler { public: StateMachineEventHandler( ) { }; virtual ~StateMachineEventHandler() { }; virtual void handle(const StateMachineEvent &event) = 0; }; template<typename StateEnum, StateEnum MaxState> class StateMachine { private: class State { private: State *pTopState_; StateMachineEventHandler *pHandler_; public: State(State *pTopState, StateMachineEventHandler *pHandler) : pTopState_(pTopState), pHandler_(pHandler) { if (!pHandler) throw std::invalid_argument("Null argument!"); } void handle(const StateMachineEvent &event) { pHandler_->handle(event); if (pTopState_ && !event.isDismissed()) { pTopState_->handle(event); } } virtual ~State() { delete pHandler_; } }; typedef std::array<State*, MaxState> StateHandlers; private: StateHandlers handlers; StateEnum currentState; public: void addState(StateEnum state, StateMachineEventHandler *pHandler) { handlers[state] = new State(NULL, pHandler); } void addState(StateEnum state, StateEnum parentState, StateMachineEventHandler *pHandler) { handlers[state] = new State(handlers[parentState], pHandler); } void start(StateEnum state) { currentState = state; } void push(const StateMachineEvent &event) { handlers[currentState]->handle(event); } }; enum State { STATE_UNKNOWN, STATE_TOP, STATE_IDLE, STATE_MAX }; class TopStateEventHandler : public StateMachineEventHandler { public: void handle(const StateMachineEvent &event) { cout<<"Top event"<<'\n'; } }; class IdleStateEventHandler : public StateMachineEventHandler { public: void handle(const StateMachineEvent &event) { cout<<"Idle event"<<'\n'; //event.dismiss(); } }; int main() { StateMachine<State, STATE_MAX> machine; machine.addState(STATE_TOP, new TopStateEventHandler()); machine.addState(STATE_IDLE, STATE_TOP, new IdleStateEventHandler()); machine.start(STATE_IDLE); machine.push(StateMachineEvent()); machine.push(StateMachineEvent()); }
run
|
edit
|
history
|
help
0
thread
მატრიცა
Longest Consecutive Subsequence
threadpool02
stl_sizeof.cc
Undefined behavior
Date n Time Macros
LIS
process memory structure
Test 16(2020)