I am implementing a finite state machine where all possible states are stored within a std::tuple
.
This is a minimum compiling example of the problem I am facing and its godbolt link https://godbolt.org/z/7ToKc3T3W:
#include <tuple>
#include <stdio.h>
struct state1 {};
struct state2 {};
struct state3 {};
struct state4 {};
std::tuple<state1, state2, state3, state4> states;
template<size_t Index>
void transit_to()
{
auto state = std::get<Index>(states);
//Do some other actions over state....
}
void transit_to(size_t index)
{
if (index == 0) return transit_to<0>();
if (index == 1) return transit_to<1>();
if (index == 2) return transit_to<2>();
if (index == 3) return transit_to<3>();
}
int main()
{
for(int i=0; i<=3; ++i)
transit_to(i);
}
In my case, I would like to change the void transit_to(size_t index)
implementation to some template construction where all the boiler plate code can be simplified in case I add new states during development.
The only constraints are:
Use C++17 or below (sorry, no c++20 fancy features please).
Do not change interface (do not propose accessing by type or so on things).