C++ templates and operator overloading allow for a lot of interesting programming techniques to be implemented. One of the interesting ones is creating functions that can be passed around like objects.

Normally, in C and C++, functions are just places in memory where certain chunks of code begin. They aren't first-class things that can be passed to other functions. So, if functions can't be made to behave like objects, why don't we make objects behave like functions?

thats some pretty neat sh*t ... i think functors exists in C/C++ (pointers to functions) that can be passed around as pointers

wtd

Posted: Sun Jun 13, 2004 12:00 am Post subject: (No subject)

Indeed. for_each and its like will also accept simple functions.

code:

#include <iostream>
#include <algorithm>

void print(float data)
{
std::cout << data;
}

int main()
{
using namespace std;

float a[] = { 1.32, 4.98, 3.14159 };

for_each(a, a + 3, print);
}

In C++ this operates on fairly simple polymorphism. The for_each function is templated, so the type of the third argument (the function pointer or function object) can be anything, so long as it responds to the () operator with a single argument.

Function pointers, especially as they must be dealt with in C and can be dealt with in C++ are powerful, but also quite dangerous and difficult and clumsy to wield. Function objects yield greater simplicity and yet greater flexibility as well.