3 ms·
So in other words the author isn't used to boost::bind and stl algorithms and complains that he doesn't understand code written with both? First of all today y
by shin_lao 16y ago
So in other words the author isn't used to boost::bind and stl algorithms and complains that he doesn't understand code written with both?
First of all today you would rather use a lambda which is easier to understand.
The advantage of the second code is that it's generic and less error prone. You can't get the loop wrong. You can change the addition by any operation very easily, and the compiler will complain when you get things wrong.
fyi, the same code written with a lambda:
int Dice::total() const {
return std::accumulate(
dice.begin(),
dice.end(),
0,
[&](size_t v, const Die & d) -> size_t { return v + d.faceValue(); });
);
}
For more information about why the second version is better, I advise the book "Elements of programming".
ps: the spelling error introduced by the author prevents the code from compiling, so the argument doesn't hold
- beagle3 16y agoerrr, no. It is in no way more generic or less error prone. Just asserting that does not make it so. You _can_ get the loop wrong, if you accumulate(dice1.begin(), dice2.end(), ...) for example, or switching the begin() and the end(). You can just as easily change the addition operation to anything else in the non-boost/stl version. In the 2nd version, when you _do_ make a mistake, if the compiler catches at you get an error message that's totally unreadable with 2000 character error lines. And if the compiler doesn't catch it, and it causes a runtime problem, it is also extremely awkward to backtrace. Not to mention, you need the latest-and-greatest compiler to do the lambda thingy, for no obvious benefit.
- shin_lao 16y agoMost STL implementations catch the two errors you gave in debug mode (switching begin and end, using two different containers, etc.), and many more! As for the compiler giving crazy errors, it's true for g++ mainly. VC10 and most of all clang give intelligible messages.
- beagle3 16y agoI haven't been following STL implementations recently, but that definitely wasn't the situation even in 2007 (Over 10 years after STL was finalized..); In fact, the only implementation that it did back then was STLPort, at a huge performance hit, and only at runtime. And what you say about compilers is EXACTLY why I wrote the "latest and greatest". It's only recent clangs that can give intelligible messages for C++ (if at all) because Clang C++ support is not even ready for production yet. VC++ 2005 (last I used) did not get give reasonable errors.
- stcredzero 16y agoThe argument does hold. Some code doesn't compile immediately. Also, Zed's code is understandable by even a programming novice. Your example strikes me as gratuitous adulation of the abstruse.
- spooneybarger 16y agothe spelling error was intentional. see the end of the article.