Reputation: 105
I would like to do something like this:
int a(int a, int b)
{
return 0;
}
int main()
{
int n = 2;
int (*b)(int) = a(a = n);
return 0;
}
I want to achieve it because I want to be able to pass a function as argument to another function but with some values defined.
How can I achieve it?
Upvotes: 0
Views: 85
Reputation: 122133
Suppose your other function is this:
using func_ptr_t = int(*)(int);
void other_func(func_ptr_t f) {
f(3);
}
Then you can use a lambda expression to bind one of the parameters:
int foo(int a, int b) // dont use same name for function and its argument
{
return 0;
}
int main() {
auto f = [](int b){ return foo(2,b); };
other_func(f);
}
If you want to capture the paramter to bind you cannot convert the lambda to a function pointer. Functions don't have state. One options is to make other_func
a template:
template <typename F>
void other_func(F f) { f(3); }
int foo(int a, int b) { return 0; }
int main() {
int n = 2;
auto f = [n](int b){ return foo(n,b); };
other_func(f);
}
However, now different instantations of other_func
are different functions. Sometimes this isn't desired, then you need some form of type erasure, for example via std::function<int(int)>
.
Upvotes: 1