YiFei YiFei - 26 days ago 11
C++ Question

Call a function with parameter from a pack of functors in variadic template

I had a (lambda) function and a lot of functors passed as variadic argument pack into a third function. The signature looks like

template<typename F, typename... G>
ret_t call(F&& func, G&&... getters);

shall have as many as argument as the number of

Now I need to call
with the return value of
called against a hard-coded (constexpr) constant determined otherwise. So untemplated code might look like

return func(getters_1(0), getters_2(0), getters_3(0) /* , ... */);

Of course I want to automate the process with template metaprogramming.

I want to avoid a temporary array or whatever intermediate container. (This is not aimed to that generic, I know the return type of getters.) I want it to be passed to the function as directly as possible so as to enable optimization and avoid waste of memory.

I could have wrapped F with many levels of closure of lambda, each wraps one parameter to it, and hope the best from compiler, but anyways I'm asking for better and clearer ways to do it.

Answer Source

If I understood you correctly you want something like this:

template<typename F, typename... G>
ret_t call(F&& func, G&&... getters) {
    return std::forward<F>(func)(std::forward<G>(getters)(0)...);