std::for_each(my_data.begin(), my_data.end(),
[&result](const auto & what) {
result += what;
});
This is an answer that I got from Quora. I asked why did C++ adopt lambdas. Someone responded with these two pieces of code, the above using lambdas and the below otherwise. They are supposed to be equivalent, and the difference in code highlights the advantage of lambdas.
template <typename T>
class add_to_impl {
T & m_result;
public:
add_to_impl(T & to): m_result(to) {}
void operator () (const T & what) { m_result += what; }
};
template <typename T>
add_to_impl<T> add_to(T & result) {
return add_to_impl<T>(result);
}
// ... other bunch of stuff
// ... somewhere else ...
std::for_each(my_data.begin(), my_data.end(), add_to(result));
However, I do not see how the add_to function will generate the equivalent behavior to the lambda.
From reading the lambda, "result" seems to be a global variable. And in my head I am thinking that the add_to function should be implemented as below in order to be equivalent to the lambda:
add_to_impl<T> result; //result being some global variable
template <typename T>
void add_to(T & what) {
result(what); // adding to result, matching what the lambda code does.
}
No, lacking any other context is a name error, as there is nothing called
result
in scope. Presumably it is declared in the code not shown.The function object dance shown is equivalent to the lambda, but as @Someprogrammerdude notes, it's better to write something like
assuming we are talking about a type for which
+
,=
and+=
do consistent things