C++ using function as parameter

后端 未结 3 993
臣服心动
臣服心动 2020-12-29 06:37

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

Suppose I have a function called

相关标签:
3条回答
  • 2020-12-29 06:54

    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
    
    0 讨论(0)
  • 2020-12-29 07:05

    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 funct2(int a) {cout << "hello " << a << endl ;}
    
    void funct(int a, function<void (int)> func) {func(a);}
    
    int main() {
        funct(3,funct2);
        return 0;}
    

    output : hello 3

    0 讨论(0)
  • 2020-12-29 07:13

    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)
    }
    
    0 讨论(0)
提交回复
热议问题