Reputation: 13886
I know member function pointers are a bit tricky, and I can call it if the function pointer isn't a member of the class itself, but can't seem to do it if it's a member of the class:
struct Window
{
virtual void handleEvent() {};
void (Window::*pHandleEvent)();
};
int main()
{
Window w;
void (Window::*fnptr)() = &Window::handleEvent;
(w.*fnptr)(); // Works fine calling a local func ptr
w.pHandleEvent(); // Calling its own member pointer doesn't work
// Err: Expression preceding parentheses of apparent call must have
// (pointer-to) function type
(w.*pHandleEvent)(); // Doesn't work
//Err: identifier "pHandleEvent" is undefined
(w.*Window::pHandleEvent)(); // Doesn't work.
// Err: A non-static member reference must be relative to a specific object.
}
Upvotes: 0
Views: 94
Reputation: 170044
With C++17 you can just rely on std::invoke
for all your pointer to member needs:
std::invoke(w.pHandleEvent, w);
First argument is the pointer to member, the second is the object, or a pointer to it. And all the syntactical business is taken care of for you.
Upvotes: 1
Reputation: 39768
You need to specify two Window
objects: the one whose pointer to use and the one on which to call the method. If they’re the same, it’s
(w.*w.pHandleEvent)();
Note the precedence: if you instead have A Window::*ptm;
and want a member of the A
object, it’s (w.*ptm).a_member
.
Upvotes: 4