如何使用不同的参数在C++中多次调用函数

Vic*_*lea 6 c++ functional-programming c++11

我有下一个代码:

object a,b,c;
fun (a);
fun (b);
fun (c);
Run Code Online (Sandbox Code Playgroud)

我想知道是否有任何方法可以在C++ 98或C++ 11中做类似的事情来:

call_fun_with (fun, a, b, c);
Run Code Online (Sandbox Code Playgroud)

谢谢

gal*_*p1n 7

这是一个可变参数模板解决方案.

#include <iostream>

template < typename f_>
void fun( f_&& f ) {}

template < typename f_, typename head_, typename... args_>
void fun( f_ f, head_&& head, args_&&... args) {
    f( std::forward<head_>(head) );
    fun( std::forward<f_>(f), std::forward<args_>(args)... );
}

void foo( int v ) {
    std::cout << v << " ";
}

int main() {
  int a{1}, b{2}, c{3};
  fun(foo, a, b, c );
}
Run Code Online (Sandbox Code Playgroud)


Jar*_*d42 6

您可以使用variadic模板使用以下内容:

template <typename F, typename...Ts>
void fun(F f, Ts&&...args)
{
    int dummy[] = {0, (f(std::forward<Ts>(args)), 0)...};
    static_cast<void>(dummy); // remove warning for unused variable
}
Run Code Online (Sandbox Code Playgroud)

或者在C++ 17中,使用折叠表达式:

template <typename F, typename...Ts>
void fun(F&& f, Ts&&...args)
{
    (static_cast<void>(f(std::forward<Ts>(args))), ...);
}
Run Code Online (Sandbox Code Playgroud)

现在,测试一下:

void foo(int value) { std::cout << value << " "; }

int main(int argc, char *argv[])
{
    fun(foo, 42, 53, 65);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


JBL*_*JBL 5

使用C++ 11,您可以这样使用std::function(编写IMO非常快)

void call_fun_with(std::function<void(int)> fun, std::vector<int>& args){
    for(int& arg : args){
        fun(arg);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,更通用一点:

template<typename FTYPE>
void call_fun_with(FTYPE fun, std::vector<int>& args){
    for(int& arg : args){
        fun(arg);
    }
}
Run Code Online (Sandbox Code Playgroud)

实例

实例,模板版

注意:std::function必须按以下方式指定模板参数:return_type(arg1_type, arg2_type,etc.)

编辑:一个替代方案可能是使用std::for_each它实际上做了几乎相同的事情,但我不喜欢语义,这更像是"对于这个容器中的所有东西,做......".但那只是我和我(也许是愚蠢的)编码方式:)