fenbf / cppstories-discussions

4 stars 1 forks source link

2023/finite-state-machines-variant-vending-cpp/ #123

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Finite State Machine with std::variant - Vending Machine - C++ Stories

In my last article, we discussed Finite State Machines based on std::variant and some cool C++17 techniques. Today I want to go further and show you an example of a Vending Machine implementation. Here’s the previous article Finite State Machine with std::variant - C++ Stories States & Events   Here’s a basic diagram that illustrates how the machine is going to work:

https://www.cppstories.com/2023/finite-state-machines-variant-vending-cpp/

nbonnec commented 1 year ago

To avoid writting all overloads, you could check for their presence with require clauses :

state_ = std::visit(helper::overload{
            [this](const auto& state, const auto& evt) {
                if constexpr (requires { onEvent(state, evt); }) {
                    return onEvent(state, evt);
                }
                return state;
            }
        }, state_, event);
kreijack commented 1 year ago

Interesting, however I think that author wanted to call VendingState onEvent(const auto&, const auto&); when no match between state/event is found.