1

is there a way to pass a function to another function where this passed function would be called inside the second function with the parameters given while passing it. However, the function passed can have different parameters.

I do not want to run the function with data from inside the calling function, just the parameters i passed when calling the function that does the actual call. Basically a periodic check to see if it's ok to continue.

An example of what i'm trying to do:

bool CheckSomething1 (int a, int b) { /* some code */ }
bool CheckSomething2 (int a, int b, int c) { /* some code */ }

bool WaitForTrue ( something funct something.. )
{
    while (! funct) {
        /* do some work */
    }   
}

int _tmain(int argc, _TCHAR* argv[])
{
    WaitForTrue(CheckSomething1(1, 2));

    WaitForTrue(CheckSomething2(1, 2, 3));

    return 0;
}

Edit: Basically i'm looking for a way to pass a function with a different number of parameters that can be different types to another function and run it, but the parameters called can be different each time when passing them, but stay the same while in the function to which it is passed.

  • I think you can find some inspiration [here](http://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c?rq=1). By the way, why are you trying this? is it simplier to call the function `CheckSomething` inside `WaitForTrue`? – Emi987 Apr 09 '14 at 08:23
  • Ever heard of a [Function Pointer](http://en.wikipedia.org/wiki/Function_pointer#Example_in_C) ? – CinCout Apr 09 '14 at 08:25
  • basically i need to put in place a system that calls functions in a third party dll, but i need to retry a couple of times if they return failure (serial bus + motor control). So i'd like to have a funtion i can call with those 3rd party functions which retry's a couple of times before returning failure. Building the retry code around each call would probably make my code three times as large and unreadable. – Kristof Nachtergaele Apr 09 '14 at 08:29
  • Yes, using function pointers, but basically i'm wondering if there is a way to pass a function without having to define it's parameters and just call the function with those parameters as i passed it to the other function. I don't need to change the parameters after i passed them. – Kristof Nachtergaele Apr 09 '14 at 08:33
  • Possible duplicate of http://stackoverflow.com/q/2535631/3168666 – Helmut Grohne Apr 09 '14 at 08:37

1 Answers1

0

What you're looking for is std::bind.

See the link above for a brief example of how it works.

Another way you may implement this kind of control style (which is already popular in functional programming, see CPS) is via currying, although it's not-so-easy to express in C++.

kvanbere
  • 3,289
  • 3
  • 27
  • 52