qn on method pointers

so I want to create a class with a utilty method that takes as a parameter a pointer to another method in the same class.
How do I go about
1) declaring said parameter,
2) making the call to said method and passing in the argument and
3) using the method pointer to (invoke the call within the utility method)
1
2
3
4
5
6
7
8
class Foo {
   typedef void (Foo::*Method)( int arg );

  public:
   void utility_method( Method m, int arg ) {
       (this->*m)( arg );
   }
};


I always recommend boost::function and boost::bind as a better solution though.
So if I want to do it without the typedef would this way do? Did I commit any bad programming habits?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

class TestClass
{
//      typedef void (TestClass::*Method)();

        public:
/*
                void utilityMethod( Method m )
                {
                        (this->*m)();
                }
*/

                void utilityMethod( void (TestClass::*m)() )
                {
                        (this->*m)();
                }

                void printString()
                {
                        cout << "Hello World" << endl;
                }

                void call()
                {
                        utilityMethod( &TestClass::printString );
                }

};
It looks fine, but I would suggest typedefing the function pointer so it looks less ugly.
many thanks for the help, oh one more thing, if the method is a const method and I want a pointer to it, I would also have to add the const in the pointer declaration right?
Last edited on
Topic archived. No new replies allowed.