C++11 State Machines

Written by on February 8, 2016 in C and C++, Programming

I recently decided to take some time to learn about the new features in C++11 while working on a project at home. C++11 has added some really nice features such as native thread support, regular expressions, safe pointer types, and variadic templates. While working on my project, I found myself needing a flexible class which would allow me to express a finite state machine (FSM) without excessive sub-classing. I also wanted to be able to select the types for states and events (transitions), which lead me down the path of developing a state machine template class. I wanted to be able to make defining a FSM as easy as the tradition C state table driven model but with better lookup times. Additionally, the class should support event callbacks should you choose to define one. The following example shows a state machine which uses std::string as the state and event. These could easily be replaced by an enum of states and enum of events.

This code results in the following output:


This output shows the all of the states and events as well as if the state is an accepted state or a terminal state. Accepted state can be used for pattern parsing and  terminal state means there are no transitions out of that state. The bottom half of the output shows the callbacks function output. The callbacks can be implemented in multiple functions or a single function depending on one’s needs.

The event callback function has the following definition:

The entry/exit callback function has the following definition:

Lookup times are improved by relying on std::set<state> and std::set<event> which are internally nested. The only the state_machine class can create instances of the state_machine::state class and only the std_machine::state class can crate instances of the state_machine::state::event class.

Hope this simple state machine can help someone from having to recreate the wheel. You can download the source here.


If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed