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?

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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?
Use a std::tuple and the same kind of approach, substituting t[Idx] for std::get<Idx>(t) and array references for the tuple.
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 I'm not sure I understand. I'd recommend making another question which details your issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.