gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:04:14 24 4
gpt4 key购买 nike

我有下一个代码:

object a,b,c;
fun (a);
fun (b);
fun (c);

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

call_fun_with (fun, a, b, c);

谢谢

最佳答案

这里是可变模板解决方案。

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

关于c++ - 如何在 C++ 中使用不同的参数多次调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21454320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com