Ace shinigami
Ace shinigami

Reputation: 1484

Function pointer which calls a function without specifying parameters

I have a function foo:

void foo(int n) {}

and I want to have a pointer that points to the function, but calls it with a specified parameter. So basically, something like this:

auto bar =  //init
bar(); //calls foo(2)

Upvotes: 0

Views: 559

Answers (2)

kmdreko
kmdreko

Reputation: 60493

If you really want a pointer, c++11 lambdas with no captures are convertible to a function pointer like so

#include <iostream>
typedef void(*functype)();

void foo(int n)
{
  std::cout << n;
}

int main()
{
  functype ptr = [](){foo(2);};
  ptr();

  return 0;
}

Upvotes: 2

Rakete1111
Rakete1111

Reputation: 49018

You can use std::bind:

auto bar = std::bind(foo, 2);

then you can call it like so:

bar();

Upvotes: 4

Related Questions