Hao Shi
Hao Shi

Reputation: 523

C++ pass a function as argument

I need to call a library function in C++, it has the form:

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:

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. I need to read data from file, do some calculations with the data to generate y. That's why I need two argument x and y in fun2. y will not be changed during calling brents_fun.

Since y is not changed, is there a way to pass fun2 to brents_fun?

Thank you.

Hao

Upvotes: 1

Views: 585

Answers (2)

Yves Calaci
Yves Calaci

Reputation: 1129

brents_fun accepts as argument a function in the form of: double someFunction(double), as you might already know. 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. Also, to post formatted code, simply select it and ctrl+k.

Upvotes: 0

Jack
Jack

Reputation: 133577

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:

  • with a lambda
  • with 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. std::bind can be polymorphic while a lambda can't, but that's not the point in your situation. I'd say just stick to the syntax you prefer.

Upvotes: 3

Related Questions