Probably only worth reading if you know C++

Jun 17, 2010 18:17

I am an unapologetic fan of C++, a programming language that unquestionably has its foibles. I am furthermore a fan of C++ templates, despite the inscrutable compiler errors and other issues. I still remember the sheer joy that came with two critical realizations about the Standard Template Library (STL). In college, I learned that the STL provides rudimentary support for functional programming in C++, using the concept of a function object. In graduate school I had the simultaneously trivial yet awesome epiphany that STL iterators don't just borrow the syntax of C pointers: pointers are iterators. Today, I had a second epiphany regarding the STL.

From a pure programming-languages perspective, my single favorite thing about working at Apple is our block extension to C, which brings me much closer to actual functional programming with C. I just realized that through the magic of templates, blocks are function objects. In particular, the following code does what you might expect:

#include
#include

int main() {
int array[] = {1, 2, 3, 4, 5};
__block int sum = 0;
void (^add_to_sum)(int) = ^(int x) { sum += x; };
std::for_each(array, array + 5, add_to_sum);
std::cout << sum << "\n";
}
HELL YES. The code I submit for my current C++ project at work is about to become more interesting.

apple, computer science

Previous post Next post
Up