jeudi 8 septembre 2022

Compile time generated array of n function pointers

I need an array of void(*relay)(void) functions which will be used as callback relays for a library which only accepts stateless void(*f)(void) callbacks. The relays will then call the actual std::function callbacks.

There is a nice solution here https://stackoverflow.com/a/63730185/1842762 which works for c++17:

std::function<void(void)> cb[nrOfRelays]; // nrOfRelays is a compile time constant

template <std::size_t ...I>
constexpr std::array<void(*)(), nrOfRelays> MakeRelays(std::index_sequence<I...>)
{
    return std::array<void(*)(), nrOfRelays>{[]{cb[I]();}...};
}

constexpr auto relays = MakeRelays(std::make_index_sequence<nrOfRelays>{});

Question: Is it possible to implement something similar for c++11? (c++11 doesn't have std::index_sequence<I...>)

Aucun commentaire:

Enregistrer un commentaire