λ
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.
Let’s omit that return-type declaration:
auto p = [](int n) { return n & 01; }; cout << p(42) << ' ' << p(43) << '\n';
0 1