Reputation: 1840
Today I was doing some catch-up on c++11 (as we have not moved on yet). One of the reasons to switch as stated by a lot of people seems to be lambda expressions. I am still unsure on how they offer something new.
For instance using c++11:
#include <iostream>
int main()
{
auto func = [] () { std::cout << "Hello world" << std::endl; };
func();
}
seems to be very similar to:
#include <iostream>
#define FUNC( )\
do { std::cout << "Hello world" << std::endl; } while(0)
int main()
{
FUNC();
}
What would lambda expressions offer me that I can't currently already do?
Upvotes: 0
Views: 885
Reputation: 122011
A less obvious benefit of lambdas when used with the standard algorithms is that the programmer is not required to think of a name for the lambda function, and naming things is considered to be a difficult task in programming.
Additionally, the code executed via the standard algorithms is often used to invoke a member function(s) on each object in the supplied range, with the name of the functor, or function, often just parroting the name of the member function being invoked and adding nothing to readability of the code. Contrived example:
struct object
{
void execute() const {}
};
void run_execute(object const& o) { o.execute(); }
std::vector<object> v;
std::for_each(v.begin(), v.end(), run_execute);
std::for_each(v.begin(), v.end(), [](object const& o) { o.execute(); });
Admittedly this is a minor benefit but still pleasant.
Upvotes: 1
Reputation: 6592
http://msdn.microsoft.com/en-us/library/vstudio/dd293608.aspx sums up the main points and more on the subject in great detail. Here is the salient excerpt:
A lambda combines the benefits of function pointers and function objects and avoids their disadvantages. Like a function objects, a lambda is flexible and can maintain state, but unlike a function object, its compact syntax doesn't require a class definition. By using lambdas, you can write code that's less cumbersome and less prone to errors than the code for an equivalent function object.
There are examples on the site showing more differences and comparisons.
Also...conventional wisdom is never use macros in C++:
http://scienceblogs.com/goodmath/2007/12/17/macros-why-theyre-evil/
Upvotes: 6