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!
no subject
The STL iterator concepts are a well thought out framework for generic programming.
You can write code like this:
…and it works regardless of the type of elephant. In C++0x, it gets even simpler:
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!