Computer Science Canada [C++] Function Objects |
Author: | wtd [ Tue Apr 06, 2004 11:09 pm ] | ||||
Post subject: | [C++] Function Objects | ||||
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? We can overload the () operator like so:
Pretty slick, huh? Now, apply it to a collection or array of things.
|
Author: | wtd [ Sat Jun 12, 2004 8:35 pm ] | ||
Post subject: | |||
A simpler example:
|
Author: | bugzpodder [ Sat Jun 12, 2004 9:38 pm ] |
Post subject: | |
thats some pretty neat sh*t ... i think functors exists in C/C++ (pointers to functions) that can be passed around as pointers |
Author: | wtd [ Sun Jun 13, 2004 12:00 am ] | ||
Post subject: | |||
Indeed. for_each and its like will also accept simple functions.
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. |