State is a design pattern meant to help change the behavior of an object when its internal state changes. The behavior for different states should be independent of each other so that adding new states doesn't affect the current ones. The simple approach of implementing all the behavior in the stateful object doesn't scale and is not open for extension. Using the state pattern, new behavior can be added by introducing new state classes and defining the transitions between them. In this section, we'll show a way to implement states and a state machine leveraging std::variant and statically polymorphic double dispatch. In other words, we'll build a finite state machine by joining the state and visitor patterns in a C++ way.
First, let's define our states. In our example, let's model the states of a product in a store. They can be as follows:
namespace state { struct Depleted {}; struct Available { int count; }...