C++ Call Pointer To Member Function
I have a list of pointers to member functions but I am having a difficult time trying to call those functions... whats the proper syntax?
typedef void (Box::*HitTest) (int x, int y, int w, int h);
for (std::list<HitTest>::const_iterator i = hitTestList.begin(); i != hitTestList.end(); ++i)
{
HitTest h = *i;
(*h)(xPos, yPos, width, height);
}
Also im trying to add member functions to it here
std::list<HitTest> list;
for (std::list<Box*>::const_iterator i = boxList.begin(); i != boxList.end(); ++i)
{
Box * box = *i;
list.push_back(&box->HitTest);
}
Pointers to non-static member functions are a unique beast with unique calling syntax.
Calling those functions require you to supply not just named parameters, but also a this
pointer, so you must have the Box
pointer handy that will be used as this
.
(box->*h)(xPos, yPos, width, height);
Calling a member function through a pointer to member function has a particular syntax:
(obj.*pmf)( params ); // Through an object or reference.
(ptr->*pmf)( params ); // Through a pointer.
Although ->*
can be overridden, it isn't in the standard
library iterators (probably because it would require overrides
for every possible function type). So if all you've got is an
iterator, you'll have to dereference it and use the first form:
((*iter).*pmf)( params );
On the other hand, iterating over a the pointer to members themselves doesn't have this problem:
(objBox.*(*i))( params ); // If objBox is an object
(ptrBox->*(*i))( params ); // If ptrBox is a pointer
(I don't think you need the parentheses around the *i
, but the
pointer to member syntax is already special enough.)
From my "award winning" ;-) answer about delegates (available at https://stackoverflow.com/questions/9568150/what-is-a-c-delegate/9568226#9568226) :
Typedef the pointer to member function like this:
typedef void (T::*fn)( int anArg );
Declare one like this:
fn functionPtr = &MyClass::MyFunction
Call it like this:
(MyObject.*functionPtr)( argument );