gerald_duck: (ascii)
Gerald the cuddly duck ([personal profile] gerald_duck) wrote in [personal profile] simont 2011-03-17 05:24 pm (UTC)

Seriously, seriously, I know there's lots to hate in C++, starting with Bjarne Stroustrup having been born and working through to C++0x's lambda function syntax, but generic programming is one thing it gets more right than any other language I've seen.

The STL iterator concepts are a well thought out framework for generic programming.

You can write code like this:

for (Elephant::iterator i=elephant.begin(); i!=elephant.end(); ++i) {
    // loop body executed once for each elephant
}


…and it works regardless of the type of elephant. In C++0x, it gets even simpler:

for (auto &e: elephant) {
    // loop body executed once for each elephant
}


The iterator for each container type deals with the specifics of stepping through the elements of an array, a linked list, a circularly linked list, a balanced tree, a hash table, a readdir(), a circular buffer, the characters of a UTF-8 string… whatever. Because the code is generic rather than run-time polymorphic, the optimiser is told precisely what's going on for a particular use of the idiom, gets to work on the code as an inlined entirety and compiles it efficiently.

What's more, unlike a macro your generic code gets syntax checked up-front, even if full semantic checking isn't possible until it knows what type it's going to get used on.

It's things like this that make me think C++ is a strictly superior language to C, these days. And these days you can code in C++ for a $10 consumer device, so compiler unavailability is almost a non-issue. C++ code even compiles on Solaris for crying out loud!

Post a comment in response:

This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting