function pointer to a class member

五迷三道 提交于 2019-11-28 14:27:06

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() {
        // ...
    }
};

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))
    {
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!