简体   繁体   中英

C++ using function as parameter

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?

Normally, for readability's sake, you use a typedef to define the custom type like so:

typedef void (* vFunctionCall)(int args);

when defining this typedef you want the returning argument type for the function prototypes you'll be pointing to, to lead the typedef identifier (in this case the void type) and the prototype arguments to follow it (in this case "int args").

When using this typedef as an argument for another function, you would define your function like so (this typedef can be used almost exactly like any other object type):

void funct(int a, vFunctionCall funct2) { ... }

and then used like a normal function, like so:

funct2(a);

So an entire code example would look like this:

typedef void (* vFunctionCall)(int args);

void funct(int a, vFunctionCall funct2)
{
   funct2(a);
}

void otherFunct(int a)
{
   printf("%i", a);
}

int main()
{
   funct(2, (vFunctionCall)otherFunct);
   return 0;
}

and would print out:

2

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

You want:

funct( 42, funct2 );

check this

typedef void (*funct2)(int a);

void f(int a)
{
    print("some ...\n");
}

void dummy(int a, funct2 a)
{
     a(1);
}

void someOtherMehtod
{
    callback a = f;
    dummy(a)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM