|
|
|
|
|
by scott_s
5892 days ago
|
|
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<int> numbers;
int sum = 0;
// give numbers some interesting values
for_each(numbers.begin(), numbers.end(), Summation(sum));
cout << "sum of all numbers: " << sum << endl;
C++0x lambdas will generate code very similar to this. The need to explicitly define a named struct/class and function object is an obvious weakness of this technique.Although I do agree with his overall point, which is that the need to use iterators for all sequences is a code smell. It forces the programmer to work at a lower level when they often just want to say "Perform this operation on my data." |
|
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:
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:
capturing references to all variables in the enclosing scope. Neat!