C++ using function as parameter

Viewed 63029

Possible Duplicate:
How do you pass a function as a parameter in C?

Suppose I have a function called

void funct2(int a) {

}


void funct(int a, (void)(*funct2)(int a)) {

 ;


}

what is the proper way to call this function? What do I need to setup to get it to work?

4 Answers

Another way to do it is using the functional library.

std::function<output (input)>

Here reads an example, where we would use funct2 inside funct:

#include <iostream>
using namespace std;
#include <functional>

void displayMessage(int a) {
    cout << "Hello, your number is: " << a << endl;
}

void printNumber(int a, function<void (int)> func) {
    func(a);
}

int main() {
    printNumber(3, displayMessage);
    return 0;
}

output : Hello, your number is: 3

A more elaborate and general (not abstract) example

 #include <iostream>
    #include <functional>
    using namespace std;
    int Add(int a, int b)
    {
        return a + b;
    }
    int Mul(int a, int b)
    {
        return a * b;
    }
    int Power(int a, int b)
    {
        while (b > 1)
        {
            a = a * a;
            b -= 1;
        }
        return a;
    }
    int Calculator(function<int(int, int)> foo, int a, int b)
    {
        return foo(a, b);
    }
    int main()
    {
        cout << endl
             << "Sum: " << Calculator(Add, 1, 2);
        cout << endl
             << "Mul: " << Calculator(Mul, 1, 2);
        cout << endl
             << "Power: " << Calculator(Power, 5, 2);
        return 0;
    }
Related