How do I obtain a function pointer for a class member function, and later call that member function with a specific object? I’d like to write:
class Dog : A
I came here to learn how to create a function pointer (not a method pointer) from a method but none of the answers here provide a solution. Here is what I came up with:
template struct MethodHelper;
template struct MethodHelper {
using T = Ret (C::*)(Args...);
template static Ret call(C* object, Args... args) {
return (object->*m)(args...);
}
};
#define METHOD_FP(m) MethodHelper::call
So for your example you would now do:
Dog dog;
using BarkFunction = void (*)(Dog*);
BarkFunction bark = METHOD_FP(&Dog::bark);
(*bark)(&dog); // or simply bark(&dog)
Edit:
Using C++17, there is an even better solution:
template struct MethodHelper;
template struct MethodHelper {
static Ret call(C* object, Args... args) {
return (object->*m)(args...);
}
};
which can be used directly without the macro:
Dog dog;
using BarkFunction = void (*)(Dog*);
BarkFunction bark = MethodHelper<&Dog::bark>::call;
(*bark)(&dog); // or simply bark(&dog)
For methods with modifiers like const
you might need some more specializations like:
template struct MethodHelper {
static Ret call(const C* object, Args... args) {
return (object->*m)(args...);
}
};