C++ Passing pointer to non-static member function

前端 未结 2 709
忘掉有多难
忘掉有多难 2021-01-23 09:28

Hi everyone :) I have a problem with function pointers
My \'callback\' function arguments are:
1) a function like this: int(*fx)(int,int)
2) an int variable: int a<

相关标签:
2条回答
  • 2021-01-23 09:46

    Functions cannot be referenced this way:

    int (*function3)(int, int) = obj.*function2;
    

    You have to pass the address of the function like this:

    int (*function3)(int, int) = std::mem_fn(&A::sub, obj);
    //                           ^^^^^^^^^^^^^^^^^^^^^^^^^
    

    The expression function2 decays into a pointer-to-function which allows it to work.

    0 讨论(0)
  • 2021-01-23 09:50

    I would do it with std functors, here is a simple example based off of your code:

    #include <iostream>
    #include <functional>
    using namespace std;
    
    class A{
    private:
        int x;
    public:
        A(int elem){
            x = elem;
        }
    
        static int add(int a, int b){
            return a + b;
        }
    
        int sub(int a, int b) const{
            return x - (a + b);
        }
    };
    
    void callback( std::function<int(const A& ,int,int )> fx, A obj, int a, int b)
    {
        cout << "Value of the callback: " << fx( obj, a, b) << endl;
    }
    
    int main()
    {
    A obj(5);
    
    
        std::function<int(const A& ,int,int )> Aprinter= &A::sub;
    
        callback(Aprinter,obj,1,2);
    }
    
    0 讨论(0)
提交回复
热议问题