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

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

class MyClass { .... private: int ToBeCalled(int a, char* b); typedef (MyClass::*FuncSig)(int a, char* b); int Caller(FuncSig *func, char* some_string); } 

I want to call Caller in some way, like:

 Caller(ToBeCalled, "stuff") 

and Caller call ToBeCalled with any parameters that, in his opinion, need to be passed. If at all possible, I want to keep everything enclosed in the private part of my class. In fact, I would have about 50 functions like ToBeCalled , so I see no way to avoid this.

Thanks for any suggestions. :)

+3
source share
2 answers

You are most there. You do not need a return type from typedef, it must be

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

Now you just need to use it correctly:

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

You want to pass regular FuncSig instances, not FuncSig* - a FuncSig* is a pointer to a member function pointer with an extra unnecessary level of indirection. Then you can use the arrow operator (not its official name):

 (object_to_be_called_on ->* func)(args); 

For objects without a pointer (for example, objects on the stack or references to objects), you use the dot-star operator:

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

Also, be careful with operator precedence - arrow and dot-star operators have lower priority than function calls, so you need to add extra brackets, as I already did.

+7
source

I assume you have already tried Caller(MyClass::ToBeCalled, "stuff") , but is there any specific reason why you need a function pointer? Also, send the actual compiler error.

0
source

Source: https://habr.com/ru/post/1389137/


All Articles