how to get address of member function

 

see:http://www.cplusplus.com/forum/general/136410/http://stackoverflow.com/questions/8121320/get-memory-address-of-member-function

static member function and dynamic member functions are treated differently.

we can just use std::function() to realize it

#include<iostream>
using namespace std;
class A
{
public:
    void ppp() { cout << "function ppp() was called" << endl; }
    static void bbb(void* obj){((A*)obj)->ppp(); }
};

// save addresses of object and member functions
// and then use template to help get the right class type
class Caller
{
public:
    class icaller{ public:virtual void run() = 0; };
    template<class T>
    class caller :public icaller {
    public:
        caller(T * obj, void(T::*call)()) :object(obj), func(call){}
        virtual void run(){ (object->*func)(); }
        T * object;
        void(T::*func)();
    };
    template<class T>
    Caller(T*object, void (T::*clk)()){ p = new caller<T>(object, clk); }
    icaller * p;
    void run() { p->run(); }
};

// function 2: save the addresses of object and static member functions
// then call dynamic functions through static member functions
class Callb
{
public: void setcall(void(*cb)(void *), void *obj){ callbk = cb; object = obj; }
        void run(){ (*callbk)(object); }
        void(*callbk)(void *);
        void *object;
};
int main()
{
    A a;
    void(A::*func)() = &A::ppp;
    void(*funcd)(void *) = &A::bbb;
    Caller funca(&a, &A::ppp);
    Callb funcb;
    funcb.setcall(&A::bbb, &a);
    funcb.run();
    funca.run();
    (a.*func)();
    funcd(&a);
}

 

posted @ 2017-03-29 12:19  HEIS老妖  阅读(152)  评论(0编辑  收藏  举报