Show Lecture.LambdaFunctions as a slide show.
λ
This is the Greek letter lambda.
In C++, it refers to an anonymous function, an unnamed function, a function literal.
int
”.
Here’s a boring ordinary function:
bool odd(int n) { return n & 01; } int main() { cout << odd(42) << ' ' << odd(43) << '\n'; }
0 1
Boolean values are displayed as 0
and 1
by default,
unless you use cout << boolalpha
.
bool odd(int n) { return n & 01; } int main() { bool (*p)(int) = odd; cout << (*p)(42) << ' ' << p(43) << '\n'; }
0 1
p
is a variable of type “pointer to function taking a int
and returning a bool
”.
p
is a pointer to function taking a int
and returning a bool
.
*p
is a function that takes a int
and returns a bool
.
auto
is your friendbool odd(int n) { return n & 01; } int main() { auto p = odd; cout << (*p)(42) << ' ' << p(43) << '\n'; }
0 1
auto
sure made that declaration easier!
odd
.
int foo=7;
auto p = [](int n) -> bool { return n & 01; }; cout << p(42) << ' ' << p(43) << '\n';
0 1
[](int n) -> int { return n & 01; }
is a lambda-expression
[]
is the capture-specification
[]
, but we’ll ignore that.
(int n)
is the argument list
-> bool
specifies the return type
{ return n & 01; }
is the body
;
at the end of the first line.
The return-type may be deduced using auto
:
auto p = [](int n) { return n & 01; }; cout << p(42) << ' ' << p(43) << '\n';
0 1
What is the return-type of the lambda-expression
pointed to by p
?
Even the arguments can be auto
:
auto twice = [](auto v) { return v + v; }; cout << twice(3) << '\n' << twice(2.34) << '\n' << twice("Jack"s) << '\n' << twice('!') << '\n';
6 4.68 JackJack 66
This is more like a templated function, in that it defines a family of functions.