Reputation: 7248
My question is somewhat similar to this one: I'm using C++14 and I'm trying to "unpack" a C-style array and call a function with its content. The difference is, I need to do that in a variadic function template and pass each element of the array into something that depends on the type parameter pack.
Here is the simplified code:
template<typename T>
struct Converter {
static T convert(const char*) {
...
}
};
template<typename ... T>
void myfunction( void(*f)(T...), char* args[]) {
f(Converter<T...>::convert(args[i])...); // this is not correct but illustrates the idea
}
myfunction
here takes a pointer to a function f
accepting an arbitrary number of arguments of type T1, ... Tn. Each element of the args
array should be converted to the corresponding type before being passed to f
.
How can I do that in C++14?
Upvotes: 0
Views: 577
Reputation: 60218
Here's a solution that creates a compile time integer sequence that you can use to index args
:
template<typename ...T, size_t ...I>
void myfunction_impl(void(*f)(T...), char const* args[], std::index_sequence<I...>) {
f(Converter<T>::convert(args[I])...);
}
template<typename ... T, size_t N>
void myfunction(void(*f)(T...), char const *(&args)[N]) {
static_assert(N == sizeof...(T), "");
myfunction_impl(f, args, std::index_sequence_for<T...>());
}
Here's a demo.
This also uses the size of the array passed in, to static_assert
that it's equal to the number of parameters of the function passed in.
Upvotes: 3