function pointer to a class member

前端 未结 2 1065
慢半拍i
慢半拍i 2020-12-12 02:54

I am trying to do some like this:

class A {
    void *(*func)(void *);

    A(void *(*function)(void *)){
        func = function;
    }
}

class B {
    voi         


        
2条回答
  •  情书的邮戳
    2020-12-12 03:19

    You could create B like this:

    struct B {
        static void *real_func(void *);
        A ptr;
        B()
        :ptr(&real_func)
        {
            ...
        }
    };
    

    A static member function acts like a regular function, so you can create a function pointer for it.

    If you don't need a regular function pointer, then you can use std::function:

    #include 
    
    struct A {
        std::function func;
    
        A(std::function function)
        : func(function)
        {
        }
    };
    
    struct B {
        void *real_func(void *);
        A ptr;
        B()
        : ptr(std::bind(&B::real_func,this,std::placeholders::_1))
        {
        }
    };
    

提交回复
热议问题