Private member function that takes a pointer to a private member in the same class

前端 未结 2 659
日久生厌
日久生厌 2021-01-20 22:55

How can I do this? (The following code does NOT work, but I hope it explains the idea.)

class MyClass  
{  
    ....  
 private:
    int ToBeCalled(int a, char*         


        
2条回答
  •  走了就别回头了
    2021-01-20 23:31

    You're most of the way there. You're missing the return type from the typedef, it should be

    typedef int (MyClass::*FuncSig)(int, char*);
    

    Now, you just need to use it properly:

    int Caller(FuncSig func, int a, char* some_string)
    {
        return (this->*func)(a, some_string);
    }
    

    You want to pass around plain FuncSig instances, not FuncSig* -- a FuncSig* is a pointer to a pointer to a member function, with an extra unnecessary level of indirection. You then use the arrow-star operator (not its official name) to call it:

    (object_to_be_called_on ->* func)(args);
    

    For non-pointer objects (e.g. objects on the stack, or references to objects), you use the dot-star operator:

    MyClass x;
    (x .* func)(args);
    

    Also, be wary of operator precedence -- the arrow-star and dot-star operators have lower precedence than function calls, so you need to put in the extra parentheses as I have done above.

提交回复
热议问题