Call a variable function in C ++ with an array as arguments

Suppose I have a simple variational function:

template <typename... A> void func(A... args) { //Do stuff } 

And I need another function to call arguments from an array, say:

 int arg[3] = {1,2,3}; 

call function

 func(1,2,3); 

Can this be done without changing the template function?

+5
source share
1 answer

You can write apply , which refers to an array and a functor to call with an unpacked array (you can add some excellent redirects, etc.):

 template <typename F, typename T, std::size_t N, std::size_t... Idx> decltype(auto) apply_impl (F f, T (&t)[N], std::index_sequence<Idx...>) { return f(t[Idx]...); } template <typename F, typename T, std::size_t N> decltype(auto) apply (F f, T (&t)[N]) { return apply_impl(f, t, std::make_index_sequence<N>{}); } 

Then name it like this if foo is a functor class:

 apply(foo{}, a); 

If foo is just a normal template function, as in your example, you can wrap it in lambda:

 apply([](auto...xs){foo(std::forward<decltype(xs)>(xs)...);}, a); 

Live demo

+4
source

Source: https://habr.com/ru/post/1241417/


All Articles