简体   繁体   中英

Unpack C-style array along with parameter pack in C++

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM