0

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)
1
  • 1
    This can't be done with a regular function pointer without the use of nonportable features. Commented Apr 12, 2016 at 15:13

2 Answers 2

4

You can use std::bind:

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

then you can call it like so:

bar();
Sign up to request clarification or add additional context in comments.

2 Comments

if I want to make a vector of these how would I do that
@Julian bar would have a return type of void and no arguments. You can use std::function as a type to the vector: std::vector<std::function<void(void)>> v;
2

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.