Joining a pointer and member pointer into a function pointer

139 views Asked by At

Please consider such code:

class MyClass{
public:
    void MyFunc(int x){
        std::cout << x << std::endl;
    }
};

int main(){
    MyClass* class_ptr = new MyClass();
    void (Myclass::*member_func_ptr)(int) = &MyClass::MyFunc;

    // This should output '5'.
    (class_ptr->*member_func_ptr)(5);

    /* ??? */

    // I want the following to output '5' exactly the same way as previous call.
    func_ptr(5);
}

How should I complete this code to have func_ptr(...) call the MyFunc from *class_ptr?

If it is possible, I would love to somehow join a MyClass* and a void (Myclass::*)(int) into a void (*)(int).

If not, I expect a clever usage of std::mem_fn and std::function (or other functional utilities) might do the trick.

Ideally, I'd like a C++11 solution (since e.g. std::mem_fun is now deprecated).

2

There are 2 answers

0
Mike Seymour On BEST ANSWER

You can't get a plain function pointer, but you can get a function object using bind or a lambda:

auto bound = std::bind(member_func_ptr, class_ptr, std::placeholders::_1);
auto lambda = [=](int x){return (class_ptr->*member_func_ptr)(x);}

bound(5);  // should output 5
lambda(5); // should output 5 too

Both of these can be converted to std::function<void(int)> if you want.

0
Dietmar Kühl On

You can't create a function pointer from a member pointer and an object pointer. What you can get is a function object with the same call notation using, e.g., std::bind():

std::bind(member_func_ptr, class_ptr, _1)

You can the use this function object to initialize, e.g., a std::function<void(int)>.