Finite State Machine with std::variant - Vending Machine
In this article, the author explores the implementation of a Vending Machine using the std::variant technique for states and events. The article begins by discussing Finite State Machines based on std::variant and some cool C++17 techniques. It then dives into the Vending Machine implementation.
The author explains that each state and event in the Vending Machine is represented by a separate small structure, which allows for flexibility and avoids issues that arise when using enum values. The article provides code examples for the states and events, showcasing the advantages of using small structures.
Moving on, the article introduces the core part of the Vending Machine, which includes a class that holds a registry of available items. The primary member function, processEvent, is responsible for accepting an event and propagating it to the states and proper OnEvent overloads. The article provides code snippets to illustrate this.
The article also highlights the various events in the Vending Machine, with a focus on the event that selects an item. The author explains how processEvent being a member function allows for easy access to all members of the VendingMachine object, which is useful for checking the availability of items in the registry.
To demonstrate the flow of states, the article includes a code snippet and its corresponding output. The output reflects the steps of the VendingMachineTest, providing a clear understanding of how the Vending Machine operates.
In summary, the article showcases a straightforward approach to creating a Vending Machine using the std::variant technique for states and events. It emphasizes the benefits of using small structures and demonstrates how the onEvent functions can be part of the primary class, enabling access to all data members of the enclosing object.
For developers interested in further examples and optimizations, the author suggests checking out another article on FSM with std::variant and C++20 - Shopping Cart, available for C++ Stories Premium/Patreon members.
Stay tuned to Dev Radar for more articles on programming languages, frameworks, and the latest news in the industry.