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?
You can fix (or curry) function arguments using
std::bind.For example,
foo2could beYou could read this as:
A call to
foo2is like a call tofoowhere the first argument is the first argument to thefoo2call and the second argument is2.The could be done with a lambda function:
See the above in action.
Finally, if you cannot use C++11 then there’s the equivalent
boost::bind.