A static member function is just a regular free function with a funny name. A pointer to a function is compatible with a pointer to a static member function.
A non-static member function is instead a function that receives and extra implicit hidden this
parameter as first parameter.
However a pointer to a non-static member function is not compatible with a pointer to a function.
To call a non-static member function using a pointer to member function you need to provide an instance... and also the syntax is quite strange: (x.*member_ptr)(...)
if x
is an object reference, or (x->*member_ptr)(...)
if x is a pointer.
A pointer to a non-static member function and a pointer to a function are incompatible types and there's no portable way to convert one in the other.
If you know the instance and you want to have a callable object to invoke one of its non-member function you can use (with C++11) an std::function
wrapping a lambda.
#include <functional>
#include <string.h>
#include <iostream>
struct Foo {
int x;
Foo(int x) : x(x) {}
void bar() { std::cout << x << std::endl; }
static void baz() { std::cout << "Here\n"; }
};
int main(int argc, const char *argv[]) {
void (Foo::*f)() = &Foo::bar; // Non-static function member pointer
void (*g)() = &Foo::baz; // Static member function = function
Foo x(42);
(x.*f)(); // Prints 42
g(); // Prints "Here"
// Portable way to call a non-static member function just using ff()
std::function<void()> ff = [&x](){ x.bar(); };
ff(); // Prints 42 too
// Hack zone... just to show that on many compilers
// even a pointer to non-static member function is just
// a pointer to a function that accepts however `this`
// as an extra first parameter.
void (*hack)(void *);
memcpy(&hack, &f, sizeof(hack));
hack(&x); // Prints 42 too on g++/clang++ (NOT PORTABLE!!)
return 0;
}