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).
You can't get a plain function pointer, but you can get a function object using
bindor a lambda:Both of these can be converted to
std::function<void(int)>if you want.