简体   繁体   English

从可变参数模板中的一堆函子中调用带有参数的函数

[英]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. 我有一个(lambda)函数,并且许多函子作为可变参数集传递给第三个函数。 The signature looks like 签名看起来像

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

and F shall have as many as argument as the number of getters given. F应具有与给定的getters数量一样多的参数。

Now I need to call func with the return value of getter called against a hard-coded (constexpr) constant determined otherwise. 现在,我需要使用针对另外确定的硬编码(constexpr)常量调用的getter返回值来调用func 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. (这不是针对该泛型的,我知道getter的返回类型。)我希望将它尽可能直接地传递给该函数,以实现优化并避免浪费内存。

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. 我本可以用许多级别的lambda闭包包装F,每个闭包都包装一个参数,并希望从编译器中得到最好的效果,但是无论如何,我一直在寻求更好,更清晰的方法。

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)...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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