Lambda Expressions in C++

pviafore 665 views 19 slides Mar 16, 2017
Slide 1
Slide 1 of 19
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19

About This Presentation

A brief talk given at HSV.cpp meetup on 3/15/17 concerning Lambdas in C++

Video is here: https://youtu.be/5splHkTJ2LY


Slide Content

[](){}(); Or How I Learned To Stop Worrying and Love the Lambda Pat Viafore HSV.cpp Meetup 3/15/2017

Lambda Expressions

Lambda Expressions Lambda Calculus Church-Turing Thesis Conversion and Reduction Complicated Mathematics Functional Programming Underpinnings of Computer Science Lisp?

Anonymous Functions

[](){}

[](){}

[]() {} Function Body

void print(std::function<bool()> func) { std::string str = func() ? "true" : "false"; std::cout << str << “\n”; } auto isFiveGreaterThanThree = []() { return 5 > 3; } ; print(isFiveGreaterThanThree);

[] () {} Parameters Function Body

void print(int param, std::function<bool( int )> func) { std::string str = func( param ) ? "true" : "false"; std::cout << str << “\n”; } auto isGreaterThanThree = [] (int num) { return num > 3; }; print(5, isGreaterThanThree);

[] () {} Capture List Parameters Function Body

void print(int num, std::function<bool(int)> func) { std::string str = func(num) ? "true" : "false"; std::cout << str << “\n”; } i nt target = 3; auto isGreaterThan = [ target ](int n){ return n > target ; }; target = 6; print(5, isGreaterThan);

Capture List By Value By Reference [this] [a,b] [=] [&a,&b] [&] Prefer Explicit Captures Over Default Captures

class A { public: int x; A(): x(10) {} std::function<bool()> getLambda() { return [=] (){ return x+2; }; } }; int main() { A* a = new A(); auto lambda = a->getLambda(); delete a; lambda(); } This is implicitly this->x. The this parameter is what gets captured, not x.

class A { public: int x; A(): x(10) {} std::function<bool()> getLambda() { return [copy=x] (){ return copy+2; }; } }; int main() { A* a = new A(); auto lambda = a->getLambda(); delete a; lambda(); } C++14 gives us init captures, where we can initialize the variables we capture (useful for any non-local captures)

Why? Dependency Injection Pass a function to inject a dependency Functional Programming Styles Mapping and Filtering just got a whole lot easier Algorithm Library auto isSpecial = [](MacAddress& mac){ return MacAddress::ItuAddress == mac; }; any_of(macs.begin(), macs.end(), isSpecial ); count_if(macs.begin(), macs.end(), isSpecial ); replace_if(macs.begin(), macs.end(), isSpecial , MacAddress::BlankMacAddress); sort(ips.begin(), ips.end(), [](IpAddressV4& ip1, IpAddressV4& ip2) { return ip1.getNetworkByteOrder() < ip2.getNetworkByteOrder()); });

[] () {} Capture List Parameters Function Body ();

Twitter: @PatViaforever