CS253: Software Development with C++

Spring 2019

Lambda Functions

Show Lecture.LambdaFunctions as a slide show.

CS253 Lambda Functions

Lambda

λ

This is the Greek letter lambda.

In C++, it refers to an anonymous function, an unnamed function, a function literal.

Functions

A function

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.

Pointer to a function

bool odd(int n) { return n & 01; }

int main() {
    bool (*p)(int) = odd;
    cout << (*p)(42) << ' ' << p(43) << '\n';
}
0 1

auto is your friend

bool 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!

There must be a better way.

λ-expressions

auto p = [](int n) -> bool { return n & 01; };
cout << p(42) << ' ' << p(43) << '\n';
0 1

λ-expressions

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?

Generic λ-expressions

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.

Use

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2019-05-12T16:28

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building