Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using parameterized functions c++

say I have a C++ function

int foo(int x, int y){
   return x+y ;
}

Is there a way to create a "parameterized" version of this function?

What I mean is that starting from foo() I would like to define function pointers that have y fixed to a specific values, the equivalent of creating the function foo2() like this:

int foo2(int x){
  return foo(x,2);
}

If not with function pointers, which can be an alternative to have a similar behaviour?

like image 993
lucacerone Avatar asked May 29 '26 10:05

lucacerone


1 Answers

You can fix (or curry) function arguments using std::bind.

For example, foo2 could be

auto foo2 = std::bind(foo, std::placeholders::_1, 2);

You could read this as:

A call to foo2 is like a call to foo where the first argument is the first argument to the foo2 call and the second argument is 2.

The could be done with a lambda function:

auto foo2 = [] (int x) { return foo(x, 2); }

See the above in action.

Finally, if you cannot use C++11 then there's the equivalent boost::bind.

like image 97
Jon Avatar answered Jun 01 '26 05:06

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!