我有一个以double(* function)(double t,double y)为参数的过程.现在我有一个像double fce(double t,double y,int a)这样的函数,我想用一个填充的参数将它传递给我的程序,类似于fce(,, 5),使其成为双fce(double t,double y)但我找不到用C或C做的方法.
解决方法:
在c++(因为您询问C或C),您可以使用std::bind执行此操作.
有关详细信息,请查看this answer.
using namespace std::placeholders; // for _1, _2, _3...
// Fix first argument as 10
auto fce_third_arg_is_5 = bind(fce, 5, _3);
/* foo(function); */
foo(fce_third_arg_is_5);
在c中,您可以通过编写新的转换器功能来完成此操作
/* Can be used only in global scope */
#define GEN_FUNC(X) double templated_fn_##X(double t, double y) {return fce(t, y, X);}
GEN_FUNC(5);
...
/* foo(function); */
foo(templated_fn_5);
或通用解决方案:
static int a_val_g;
static double wrapper(double t, double y)
{
return fce(t, y, a_val_g);
}
function make_func(int a) {
/* Warning: Not thread safe. Subsequent call will invalidate previously returned function */
/* fn(make_func(i), make_func(42); is bad */
/* Using make_func in a multithreaded application is unsafe unless synchronized properly */
a_val_g = a;
return wrapper;
}
...
/* foo(function); */
foo(make_func(5));
标签:c-3,c,function,c++,c
来源: https://codeday.me/bug/20190728/1559238.html