C++: Higher-Order Functions

Bjarne-stroustrup
 

Pass a function as an argument to another function.

Function Pointer

Works with: g++ version 3.4.2 (mingw-special)

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.

Works with: gcc version 4.4

 

// 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

Works with: Visual C++ version 2005

#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;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.