Martí Serra
Martí Serra

Reputation: 105

How to make a pointer to a function and define some arguments to this function in C++

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

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

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

Related Questions