0

In C++, I'm trying to define a type suitable for a pointer to one of several member functions of my class cBar (all functions have the same interface, say accept an int and return void).

For now, I'm making a global type tHandler suitable for a pointer to one of several global functions accepting an additional parameter me, holding a pointer to my class cBar, as follows:

typedef void(*tHandler)(class cBar *const me, int val);

void Handler0(class cBar *const me, int val);
void Handler1(class cBar *const me, int val);

class cBar {
    tHandler fCurrentHandler;
    /*..*/
public:
    inline void cBar::CurrentHandler(int val) {
        (*fCurrentHandler)(this,val);
        }
    inline cBar() {
        fCurrentHandler = Handler0;
        CurrentHandler(0);
        }
    inline ~cBar() {
        CurrentHandler(-1);
        }
    };

This is ugly; in particular Handler0 and Handler1 should be private methods of cBar, and tHandler should be a private type.

Any clue? TIA.

fgrieu
  • 2,724
  • 1
  • 23
  • 53
  • possible duplicate of [C++ member-function pointer](http://stackoverflow.com/questions/5499155/c-member-function-pointer) – Xeo Oct 25 '11 at 14:05
  • Please search before asking, this question was asked multiple times already, the linked one is just one example. – Xeo Oct 25 '11 at 14:06
  • 1
    Right. An excuse: [C++ member-function pointer](http://stackoverflow.com/questions/5499155/c-member-function-pointer) is not tagged _Function-pointers_. – fgrieu Oct 25 '11 at 14:36

1 Answers1

4

A pointer to a member can be declared like

typedef void(Trustee::*tHandler)(int);

Here's how to use it (adaptation of your own code):

class Trustee {
    typedef void(Trustee::*handler_t)(int);
    handler_t pfCurrentHandler;
    void handlerOne(int i) { cout << "HandlerOne: " << i << endl; } 
    void handlerTwo(int i) { cout << "HandlerTwo: " << i << endl; } 
public:
    void CurrentHandler(int val) {
        (this->*pfCurrentHandler)(val);
    }
    Trustee() : pfCurrentHandler(&Trustee::handlerOne) {
        CurrentHandler(0);
    }
    ~Trustee() {
        CurrentHandler(-1);
    }
};

Pay particular attention to the operator ->*, which is not something you see every day.

See it in action.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • I get that `:` pfCurrentHandler(&Trustee::handlerOne)` sets 'pfCurrentHandler' to '&Trustee::handlerOne', but I am not familiar with this construct (is this a _brace-or-equal-initializer_?). What is the advantage versus plain 'pfCurrentHandler = &Trustee::handlerOne'? – fgrieu Oct 25 '11 at 15:48
  • @fgrieu: It's a [constructor initialization list](http://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list). In this case there is no benefit, but it's a good habit to get into. – Jon Oct 25 '11 at 15:51
  • Again, may thanks! Another century and I'll be as fluent with C++ as I am with C + preprocessor. – fgrieu Oct 25 '11 at 15:55