Section I ================ general function pointer usage
function pointer can point to 1. general c-style function 2. template c-style function 3. general c++ static member function, which is totally the same with c-style function 4. c++ static member function which was used to delegate general non-static member function. the benefit of this usage is, we can use function pointer to base class to delegate member function of derived class.
all usage can be found in the following example. run it and get a feeling.
#include #include #include #include
using namespace std;
class Base; class A;
//c or c++ static member function int (*function_pointer_c_style)(int,int); //c++ non-static member function int (A::*function_pointer_class_non_static_style)(int,int); //c++, use static-style member function to delegate non-static member function int (*function_pointer_class_static_delegate_style)(void*, int,int);
int sum(int a, int b) { cout << "call non-template c-style function" << endl; cout << a << " + " << b << " = " << a + b << endl; cout << endl; }
template int sum(A a, B b) { cout << "call template c-style function" << endl; cout << a << " + " << b << " = " << a + b << endl; cout << endl; }
template int multi(T a, int b) { cout << "function pointer which point to template function" << endl; cout << a << " * " << b << " = " << a * b << endl; cout << endl; }
class Base { public: int SumNonStatic( int a, int b) { cout << "call base class non-static member function" << endl; cout << "Base class: " << a << " + " << b << " = " << a + b << endl; cout << endl; } };
class A : public Base { public: static int Sum(int a, int b) { cout << "call class static member function" << endl; cout << a << " + " << b << " = " << a + b << endl; cout << endl; }
int SumNonStatic( int a, int b) { cout << "call class non-static member function" << endl; cout << "Derived class: " << a << " + " << b << " = " << a + b << endl; cout << endl; }