简体   繁体   中英

Joining a pointer and member pointer into a function pointer

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 eg std::mem_fun is now deprecated).

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.

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, eg, std::bind() :

std::bind(member_func_ptr, class_ptr, _1)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM