Passing methods as function parameters C++

This is more like a quick reference for myself, how to pass a method as a function argument. It turned out to be very useful for one of programming tasks. I had a lot of  "get" type methods with the same return value, and needed to construct a table of results. And passing method as argument, was a very neat solution.


First define a new type like this:

typedef int (blockItem::*NODE_METHOD) ();

nt is the methods return type. Change it accordingly.
blockItem is the class name which methods you want to access.

I tried to come up with a way where return type doesn't matter, only thing I could come up with was using QVariant, but it involves changing a lot of methods and is Qt specific. I was too lazy to do that. If anybody who is reading this, knows a way how to do it, then feel free to enlighten me and other readers by leaving a comment.

 

Then just make a function with one of the arguments the new type. Just look at the example how to use the method's pointer.

void EpicClass::callAnotherMethod(NODE_METHOD method, blockItem* myObject)
{
     cout << "Magic: " << (myObject->*method)() << endl;
}

 

The calling would be something like this:

void EpicClass::writeEpicData()
{
     for(blockItem* object : allObjects)
     {
          callAnotherMethod( &blockItem::getStock, object );
          callAnotherMethod( &blockItem::getThroughput, object );
     }
}

That's basically all it is to it. I can't seem to remember the syntax when it come to using the pointer. It's not like someone often passes method as a function argument.




ADVERTISEMENT