c++typesvariadic-templatesstate-machine

Typelist for State Machine


I have two aliases to manage a collection of states for a toy state machine using smart pointers:

using States = std::tuple<std::shared_ptr<State1>, std::shared_ptr<State2>>;
using CurrentState = std::variant<std::shared_ptr<State1>, std::shared_ptr<State2>>;

The example above has two states, but I want, say, 40. Question for my own education: how to use variadic templates (or any other strategy) to avoid repeating the 40-long typelist in both aliases? I'm trying to avoid using an external TMP library.

Possibly related question: I want the object under whose struct these aliases are defined to own the states. Is using smart pointers the way to go here if I'm concerned that every state in my machine is too large to keep all of them in the stack? Hope the question makes sense.


Solution

  • If you have a class like

    template <typename... Ts> struct States {};
    

    and you want to add those aliases to States you can do it like

    template <typename... Ts> 
    struct States 
    {
        using States_t = std::tuple<std::shared_ptr<Ts>...>;
        using CurrentState_t = std::variant<std::shared_ptr<Ts>...>;
    };