CS253 Lambda Functions
λ
This is the Greek letter lambda.
In a C++ context, it refers to an anonymous function.
int
”.
Here’s a boring ordinary function:
double half(double d) { return d/2.0; } int main() { cout << half(4.2) << '\n'; }
2.1
double half(double d) { return d/2.0; } int main() { double (*p)(double) = half; cout << (*p)(10.2) << '\n'; cout << p(8.6) << '\n'; }
5.1 4.3
p
is a variable of type “pointer to function taking a double and returning a double”.
p
is a pointer to function taking a double and returning a double.
*p
is a function taking a double and returning a double.
auto
is your frienddouble half(double d) { return d/2.0; } int main() { auto p = half; cout << (*p)(10.2) << '\n'; cout << p(8.6) << '\n'; }
5.1 4.3
auto
sure made that declaration easier!
half
.
int foo=7;
auto p = [](double d) -> double { return d/2.0; }; cout << p(8.6) << '\n';
4.3
[](double d) -> double { return d/2.0; }
is a lambda-expression
[]
is the capture-specification
[]
, but we’ll ignore that.
(double d)
is the argument list
-> double
is return type
{ return d/2.0; }
is the body
Let’s omit that return-type declaration:
auto p = [](double d) { return d/2.0; }; cout << p(8.6) << '\n';
4.3
Modified: 2017-04-13T11:32 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |