7

Suppose I have a simple variadic function like this:

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

And I need another function to call the arguments from an array, let's say:

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

call the function

func(1,2,3);

Is it possible to do this without modifying the templated function?

Fynn
  • 811
  • 2
  • 10
  • 19
  • 1
    maybe you could write a (also templated) wrapper function which applies the arguments to the original – gorhawk Jan 25 '16 at 13:55
  • try that - [Passing std::array as arguments of template variadic function](http://stackoverflow.com/questions/16834851/passing-stdarray-as-arguments-of-template-variadic-function) – malchemist Jan 25 '16 at 14:04

1 Answers1

10

You could write apply which takes a reference to an array and functor to call with the unpacked array (you might want to add perfect forwarding and such):

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 call it like this, if foo is a functor class:

apply(foo{}, a);

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

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

Live Demo

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • What if I want to pass multiple types to that template, for instance, I want to call foo("a", 1, 3.0). Do you have any hints on how to do that? – Fynn Jan 25 '16 at 16:02
  • Use a `std::tuple` and the same kind of approach, substituting `t[Idx]` for `std::get(t)` and array references for the tuple. – TartanLlama Jan 25 '16 at 18:48
  • But I also don't know a priori what kind of elements I'm getting, can be `foo("a")` or `foo(1,2.0)`. Otherwise I end up in the same problem while specifying the `std::tuple` So what I have is just a list of pairs for example, so that the second value specifies the type, can this still be done?! – Fynn Jan 25 '16 at 20:08
  • @Fynn I'm not sure I understand. I'd recommend making another question which details your issue. – TartanLlama Jan 25 '16 at 21:34