Is the type of “pointer-to-member-function” different from “pointer-to-function”?
Yep.
Consider the following function:
int f(char a, float b);
The type of this function is different depending on whether it is an ordinary function or a non-static
memberfunction of some class:
- Its type is “
int (*)(char,float)
” if an ordinary function - Its type is “
int (Fred::*)(char,float)
” if a non-static
member function ofclass
Fred
Note: if it’s a static
member function of class
Fred
, its type is the same as if it were an ordinary function:“int (*)(char,float)
”.
example code:
#include <iostream>
#include <string>
using std::string;
class Foo{
public:
int f(string str){
std::cout<<"Foo::f()"<<std::endl;
return 1;
}
};
int main(int argc, char* argv[]){
int (Foo::*fptr) (string) = &Foo::f;
Foo obj;
(obj.*fptr)("str");//call: Foo::f() through an object
Foo* p=&obj;
(p->*fptr)("str");//call: Foo::f() through a pointer
}
#include <iostream>
#include <string>
using std::string;
class Foo{
public:
static int f(string str){
std::cout<<"Foo::f()"<<std::endl;
return 1;
}
};
int main(int argc, char* argv[]){
//int (Foo::*fptr) (string) = &Foo::f;//error
int (*fptr) (string) = &Foo::f;//correct
(*fptr)("str");//call Foo::f()
}
https://isocpp.org/wiki/faq/pointers-to-members
http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm