Christoph Christoph - 3 months ago 23
C++ Question

Create a sequence of explicit function template instantiations

In C++ 11, can I build a template which explicitly instantiates a sequence of function templates into an array initialiser? What I want to achieve (please don't ask why I need that, because it's a long story) looks like

// The template I want to instantiate:
template<size_t N> void callbackTemplate(const int dummy) {
// Do something which needs to know 'N'.

// The variable I want to assign 'callbackTemplate' instantiations to:
void (*callback)(const int dummy); // This cannot be std::function, because it
// is not defined by me! It is already there and
// must be used as it is.

// This is the set of instantiations I want to prepare:
std::array<decltype(callback), 3> callbackTemplates = {
callbackTemplate<0>, callbackTemplate<1>, callbackTemplate<2>

The code above works as it is. What I want to change is the initialisation of the
array. I want the initialiser to become a template which is dependent on a compile-time constant and creates the instantiations 0..N.

The problem is somehow related to C++ static const array initialization in template class, but I did not manage to "templatise" the instantiation of the other template.


You can do this using an implementation of C++14's std::integer_sequence. Here's one.

With callback_t defined as

using callback_t = decltype (callback);

you can just pass a sequence and make use of the type deduction:

template<unsigned... Is>
array<callback_t, sizeof...(Is)> make_callback_array_impl(seq<Is...>)
    return { callbackTemplate<Is>... };

template<unsigned N>
array<callback_t, N> make_callback_array()
    return make_callback_array_impl(GenSeq<N>{});

live demo