Transcript

[](){}();Or How I Learned To Stop Worrying and Love the

Lambda

Pat ViaforeHSV.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);

[](){}

ParametersFunction 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”;}

int target = 3;auto isGreaterThan = [target](int n){ return n > target; };target = 6;print(5, isGreaterThan);

Capture ListBy 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 Libraryauto 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


Top Related