Monday, June 4, 2012

How to define a function pointer to a member function of an object

Pointer to non-static member function.
As the member functions depend on object, the point of a non-static function is actually an offset.
   1:  class A

   2:  {

   3:      int _val;

   4:      int val();

   5:  };

   6:   

   7:  int (A::*p_val) = &A::_val;

   8:  int ( A::*p_func )() = &A::val;



Pointer to static member function. As static function of a class does not depend on any object of that class, the pointer is the same as the one in C.

   1:  class A
   2:  {
   3:      static int _val;
   4:      static int val();
   5:  };
   6:   
   7:  int *p_val = &A::_val;
   8:  int (*p_func) = &A::val;



Advantages: 1. easy to call; 2. callback function

A complete example:

   1:  #include <iostream>
   2:  #include <string>
   3:  using namespace std;
   4:   
   5:  typedef void (*funchandler)();
   6:   
   7:  void register_func(funchandler f)
   8:  {
   9:      cout << "register_func" << endl;
  10:      (*f)();
  11:  }
  12:   
  13:  class A
  14:  {
  15:  public:
  16:      A() : _val( 0 ) { cout << "create A..." << endl; }
  17:      void test() { cout << "test..." << endl; }
  18:      void test1() { cout << "test1..." << endl; }
  19:      void test2() { cout << "test2..." << endl; }
  20:      int val() { return _val; }
  21:      static void test3() { cout << "test3..." << endl; }
  22:      int _val;
  23:  private:
  24:  };
  25:   
  26:  int main()
  27:  {
  28:      A a;
  29:      int ( A::*p_val ) = 0;
  30:      p_val = &A::_val;
  31:      cout << "a.*p_val: " << a.*p_val << endl;
  32:     
  33:      void (A::*p_func)();
  34:      p_func = &A::test;
  35:     
  36:      a.test();
  37:      (a.*p_func)();
  38:     
  39:      p_func = &A::test1;
  40:      ( a.*p_func )();
  41:      p_func = &A::test2;
  42:      ( a.*p_func )();
  43:     
  44:      void (* pp_func)();
  45:      pp_func = &A::test3;
  46:      (*pp_func)();
  47:     
  48:      register_func( pp_func );
  49:      return 0;
  50:  }

No comments:

Post a Comment