简体   繁体   English

C ++将函数作为参数传递

[英]C++ pass a function as argument

I need to call a library function in C++, it has the form: 我需要在C ++中调用库函数,它具有以下形式:

double brents_fun(std::function <double(double)> f);

I can call this function by the following: 我可以通过以下方式调用此函数:

double fun1(double x)
{
   return -2.0*x+1;
}

void main()
{
   brents_fun(fun1);
   return 0;
}

I want to pass another function to brents_fun , like: 我想将另一个函数传递给brents_fun ,如:

double fun2(double x, double y)
{
   return -2.0*x+y;
}

void main()
{
   y=12.0;
   brents_fun( fun2(x,y=12) );
   return 0;
}

In my real code, y is complicated. 在我的真实代码中,y很复杂。 I need to read data from file, do some calculations with the data to generate y. 我需要从文件中读取数据,用数据进行一些计算以生成y。 That's why I need two argument x and y in fun2. 这就是我在fun2中需要两个参数x和y的原因。 y will not be changed during calling brents_fun. 在调用brents_fun时,不会更改y。

Since y is not changed, is there a way to pass fun2 to brents_fun? 由于y没有改变,有没有办法将fun2传递给brents_fun?

Thank you. 谢谢。

Hao

You basically want to partially apply a function to pass it as an argument to brents_fun , this is possible and you have two ways to do it in C++11: 你基本上想要部分应用一个函数将它作为参数传递给brents_fun ,这是可能的,你有两种方法在C ++ 11中做到这一点:

  • with a lambda 有一个lambda
  • with std::bind std::bind

Both solutions: 两种方案:

double brents_fun(std::function <double(double)> f)
{
  return f(0.0);
}

double fun1(double x, double y)
{
  return x+y;
}

int main() {
  double res1 = brents_fun([](double x) { return fun1(x, 12.0); });
  double res2 = brents_fun(std::bind(fun1, placeholders::_1, 12.0));
}

While the lambda one is more suitable to optimizations in general both solutions are equivalent. 虽然lambda更适合于优化,但两种解决方案都是等价的。 std::bind can be polymorphic while a lambda can't, but that's not the point in your situation. std::bind可以是多态的,而lambda不能,但这不是你的情况。 I'd say just stick to the syntax you prefer. 我只想坚持你喜欢的语法。

brents_fun accepts as argument a function in the form of: double someFunction(double), as you might already know. brents_fun接受一个函数形式为:double someFunction(double),你可能已经知道了。 No functions of other return types, nor arguments, can be used. 不能使用其他返回类型的函数或参数。 In this particular case, you can pass the fun1 function, them sum y when you have it calculated. 在这种特殊情况下,你可以传递fun1函数,当你计算它们时,它们会相加。 Also, to post formatted code, simply select it and ctrl+k. 另外,要发布格式化代码,只需选择它并按ctrl + k即可。

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

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