For an embedded solution I want to define an array of void(*relay)(void)
functions which I use as callback relays for a library which only accepts stateless void(*f)(void)
callbacks. The relays will then call the actual std::function
callbacks.
The code below works nicely. However, I'm looking for a possibility to change the number of relay functions without having to manually type their initialization to the array. A compile time solution would be nice but initialization of the array at runtime would be fine as well.
Any chance to implement such a thing in C++?
constexpr size_t nrOfRelays = 5;
std::function<void(void)> cb[nrOfRelays]; // callbacks
void (*const relays[nrOfRelays])(void) // array of pointers to void(*relay)(void)
{
[] { cb[0](); },
[] { cb[1](); },
[] { cb[2](); },
[] { cb[3](); },
[] { cb[4](); },
};
void test(unsigned nr, std::function<void(void)> callback)
{
cb[nr] = callback;
attachCallback(nr, relays[nr]); // lib requires a void(*f)() callback
}