Finite State Machine with std::variant -- Bartlomiej Filipek
In this blog post, I’ll show you how to convert a “regular” enum-style finite state machine into a modern version based on std::variant from C++17. This technique allows you to improve design, work with value types and enhance code quality.
Finite State Machine with std::variant
by Bartlomiej Filipek
From the article:
Let’s start with a basic example:
- we want to track a game player’s health status
- we’d like to respond to events like “Hit by a monster” or “Healing bonus.”
- when the health point goes to 0, then we have to restart the game only if there are some remaining lives available
Here’s a basic diagram with states and transitions:


Registration is now open for CppCon 2023! The conference starts on October 1 and will be held
Registration is now open for CppCon 2023! The conference starts on October 1 and will be held
The latest major version of the
Registration is now open for CppCon 2023! The conference starts on October 1 and will be held
The active object design pattern decouples method execution from method invocation for objects that each reside in their own thread of control.The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.
Registration is now open for CppCon 2023! The conference starts on October 1 and will be held
A few years ago, I showed an interesting implementation for self-registering classes in factories. It works, but one step might be at the edge of Undefined behavior. Fortunately, with C++20, its new constinit keyword, we can update the code and ensure it’s super safe.
Registration is now open for CppCon 2023! The conference starts on October 1 and will be held
You may have a class that you want to participate in RVO or NRVO, but you also don’t want it to be moved. For example, it may contain a std::mutex, which is not movable. But you nevertheless have to declare a move constructor. What can you do?