The easiest and most flexible way is to use the std :: function.
Suppose I have a function (but it could be a class) that should call another function passed to it. I define this function as follows:
#include <functional> // defines std::function #include <iostream> typedef std::function<bool(int)> FunctionPtr; void myFunction (const FunctionPtr &functionPtr) { std::cout << "Before" << std::endl; functionPtr(123); std::cout << "After" << std::endl; }
The first example of using this method is the use of a global function (or a static method), for example:
bool myFunPtr(int i) { std::cout << "FunPtr:" << i << std::endl; return true; } int main() { myFunction (myFunPtr); }
I just pass a pointer to the myFunction function.
I can also use a lambda expression, for example:
int main() { myFunction ([](int i)->bool{std::cout << "Lambda:" << i << std::endl;return true;}); }
The third example (and which you probably want) should pass an instance of the class that defined the operator function, for example:
class X { public: X(std::string s) : m_s(s) {} bool operator()(int i) { std::cout << m_s << i << std::endl; return true; } private: std::string m_s; }; int main() { myFunction ([](int i)->bool{std::cout << "Lambda:" << i << std::endl;return true;}); myFunction (myFunPtr); X x1("x1:"); myFunction (x1); X x2("x2:"); myFunction (x2); }
As you can see, using std :: function, I can pass 3 different types of "function references" (function pointers, lambda and functors).
Patrick
source share