1

Suppose I have a function int func(int x, int y, int z) and I need to call it within another function 10 times, ie, int runge(int, ... , int func(int a, int b)). I know I could create 10 functions, i.e.

 int runge1(int a, int b) {return func(1, a, b);}

But, I'd like a simpler method of doing this. Basically I want to create a function pointer as such:

for(int i=0; i<10; i++)
    {
    //func would have two variables input into it, variable1, variable2
    int (*func)=func(i, variable1, variable2);
    }
Michael Wild
  • 24,977
  • 3
  • 43
  • 43
Edward Jezisek
  • 522
  • 4
  • 11
  • 1
    Sorry, your example about calling the function *10 times within another function` is not clarifying things at all. Perhaps by expanding a bit more (i.e. for `i = 1, 2, 3, ...`) your question would become clearer. – Michael Wild Mar 12 '13 at 14:07
  • Thank you for the help, sorry about my question being unclear. I need to wait a minute to accept a correct answer, but thanks for the help. – Edward Jezisek Mar 12 '13 at 14:16

3 Answers3

4

You're looking for std::bind:

std::function<int(int,int)> f = std::bind(&func, i, std::placeholders::_1, std::placeholders::_2);

This will bind i to the first argument of func and leave the remaining arguments unbound. You can then call f like so:

f(1, 2);

If you want to, you can push all of your newly bound functions into a std::vector:

using namespace std::placeholders;
std::vector<std::function<int(int,int)>> funcs;
for (int i = 0; i < 10; i++) {
  funcs.push_back(std::bind(&func, i, _1, _2));
}

If you don't have C++11, there is a boost::bind counterpart.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
1

I'm not 100% sure by your description, but it looks like you're looking to curry the function.

In C++, here's a good example: How can currying be done in C++?

Community
  • 1
  • 1
Nick Veys
  • 23,458
  • 4
  • 47
  • 64
  • that example is rather old, and those binders mentioned there are deprecated with the new standard, having `std::bind` and lambdas. – Arne Mertz Mar 12 '13 at 14:14
0

I am pretty sure you want to know std::function, Lambdas and maybe std::bind:

int func(int x, int y, int z);

typedef std::function<int(int,int)> FuncT;
std::array<FuncT, 10> functions; //or whatever container suits your needs
for (int i = 0; i < 10; ++i)
{
  functions[i] = [=](int a, int b) { return func(i,a,b); }; //with lambdas
  functions[i] = std::bind(func, i, std::placeholders::_1, std::placeholders::_2); //with bind
}

(I prefer lambdas, but that's a matter of taste...)

Arne Mertz
  • 24,171
  • 3
  • 51
  • 90