While C++0x will have proper lamdbas and closures (I've said this how many times in the past few weeks?), I think it's worth noting the "proper" way to emulate a closure in C++ is with a function object. Example: struct Summation { int& sum; Summation(int& s): sum(s) {} void operator()(int n) { sum += n; } }; vector numbers; int sum = 0; // give numbers some interesting values for_each(numbers.begin(), numbers.end(),…
Interesting. Your comment about C++0x closures inspired me to look it up on Wikipedia. The verbosity of the fragment above is greatly reduced. You had to write 'sum' or 's' lots of extra times ('Summation(sum)', 'sum(s)', 'int& sum', and 'int& s'), and you won't have to do that anymore -- according to wikipedia your function will change in C++0x to: for_each( numbers.begin(), numbers.end(), [&sum](int n) { sum += n;…
Re: Iterators: Signs of Weakness in Object-Oriented Languages
#11Of course, C++ already has std::accumulate, which is basically the same thing as a general fold or a summation, depending on which version you use. So, there isn't really much of a reason to write sum manually at all. :p