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 callbackTemplates 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
This can be done with variable template specializations.
template<class>
int callbackTemplates_v;
template<std::size_t... Indicies>
std::array<decltype(callback), sizeof...(Indicies)>
callbackTemplates_v<std::index_sequence<Indicies...>> = {callbackTemplate<Indicies>...};
template<std::size_t N>
auto callbackTemplates = callbackTemplates_v<std::make_index_sequence<N>>;
Now callbackTemplates<N> is an array of N instaniations of callbackTemplate from 0..N-1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With