четвртак, 5. јануар 2012.

Lambda Functions in C++11 - the Definitive Guide

11 is ability to create lambdafunctions (sometimes referred to as closures). What does this mean? A lambdafunction is a function that you can write inline in your source code (usually to pass in to another function, similar to the idea of a functor or function pointer). With lambda, creating quick functions has become mucheasier, and this means that not only can you start using lambda when you'dpreviously have needed to write a separate named function, but you can startwriting more code that relies on the ability to create quick-and-easyfunctions. In this article, I'll first explain why lambda is great--with someexamples--and then I'll walk through all of the details of what you can do withlambda.

Why Lambdas Rock

Imagine that you had an address book class, and you want to be able toprovide a search function. You might provide a simple search function, taking astring and returning all addresses that match the string. Sometimes that's whatusers of the class will want. But what if they want to search only in thedomain name or, more likely, only in the username and ignore results in thedomain name? Or maybe they want to search for all email addresses that alsoshow up in another list. There are a lot of potentially interesting things tosearch for. Instead of building all of these options into the class, wouldn'tit be nice to provide a generic "find" method that takes a procedure fordeciding if an email address is interesting? Let's call the methodfindMatchingAddresses, and have it take a "function" or "function-like" object.

#include #include class AddressBook

View the Original article

Нема коментара:

Постави коментар