Hacker News new | ask | show | jobs
by lincolnq 5887 days ago
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; } );
Which is semantically much less to think about. It also still has the feature / annoyance (?) of having to specifically identify which variables to capture from the environment ('sum', as a reference; it seems you can capture variables by value too).

Fortunately, it seems the C++ people even thought of that annoyance, and allow you to write:

    for_each( numbers.begin(), numbers.end(), [&](int n) { sum += n; } );
capturing references to all variables in the enclosing scope. Neat!
2 comments

Of 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

http://www.sgi.com/tech/stl/accumulate.html

Indeed. I actually use this technique in my own code, and I feel like I'm laying down pipe all over the place to make sure the captured variable gets routed to the function object correctly. Once you do it a few times, it is obviously boiler-plate code and obviously a hindrance to momentum.