-
Notifications
You must be signed in to change notification settings - Fork 392
Lambdas: When and How to Use Them
Functions have been "first-class citizens" in C++ since the C days. In a computer language, a "first class citizen" refers to any entity that can be assigned to a variable, passed to a function as an argument, and returned from a functions as value. You can do all of these things with C/C++ functions. This is how callbacks and virtual functions are implemented among other things. As an aside, an example of something that isn't a "first-class citizen" in C/C++ is types. You cannot assign int
to a variable in C, or pass a the name of a class
as an argument to a function. There are some languages, e.g., python, in which you can do these things, and a lot of cool capabilities emerge from that. In C/C++ you cannot, which partially motivates the need for templates.
Anyways, being able to pass a function as a parameter to another function is useful capability. The classic C/C++ example is the sort
which can take a custom comparison function as an argument. Here is an example where an vector of myStruct
s is sorted using a custom comparison function that compares structure name
values.
struct S_c {
std::string name;
int data;
};
bool sCompare(struct S_c const &s1, struct S_c const &s2) const { return strcmp(s1.name, s2.name) < 0; }
std::vector<struct S_c> sVec;
void myFunction()
{
...
sort(sVec.begin(), sVec.end(), sCompare);
...
}
Cool. What about this lambda stuff?
In C++11, the language added the lambda construct. At first blush, the lambda construct appears to be just a cute way of defining a single-use function directly at the point of use.
void myFunction()
{
...
sort(sVec.begin(), sVec.end(), bool [](struct S_c const &s1, struct S_c const &s2) { return strcmp(s1.name, s2.name) < 0; });
}
Cute, right? But what fundamental new capability does lambda add?