Pass a function as an argument to another function.
Function Pointer
C++ can pass function pointers in the same manner as C.
Function class template
Using the std::tr1::function class template allows more powerful usage. function<> can be used to pass around arbitrary function objects. This permits them to be used as closures.
For C++11 this is now std::function.
// Use <functional> for C++11 #include <tr1/functional> #include <iostream> using namespace std; using namespace std::tr1; void first(function<void()> f) { f(); } void second() { cout << "second\n"; } int main() { first(second); }
Template and Inheritance
#include <iostream> #include <functional> template<class Func> typename Func::result_type first(Func func, typename Func::argument_type arg) { return func(arg); } class second : public std::unary_function<int, int> { public: result_type operator()(argument_type arg) const { return arg * arg; } }; int main() { std::cout << first(second(), 2) << std::endl; return 0; }
Content is available under GNU Free Documentation License 1.2.