function pointer to a class member

前端 未结 2 1058
慢半拍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 <functional>
    
    struct A {
        std::function<void *(void*)> func;
    
        A(std::function<void *(void*)> function)
        : func(function)
        {
        }
    };
    
    struct B {
        void *real_func(void *);
        A ptr;
        B()
        : ptr(std::bind(&B::real_func,this,std::placeholders::_1))
        {
        }
    };
    
    0 讨论(0)
  • 2020-12-12 03:33

    Since real_func is not a static member function, its type cannot be void *(*)(). Instead, it is void *(B::*)() so you need to declare func accordingly:

    void *(B::*func)();
    
    // call it like this
    pointer_to_b->*func();
    

    If you are careful, you can also use pointer to A as the base class, but you must make sure that the pointer to A points to an instance of B:

    void *(A::*func)();
    

    At this point, however, you are mostly just replicating the functionality of virtual member functions. So I would recommend you use that instead:

    class A {
        virtual void *func() = 0;
    };
    
    class B {
        void *func() {
            // ...
        }
    };
    
    0 讨论(0)
提交回复
热议问题