SlideShare a Scribd company logo
1 of 25
Download to read offline
Lambda expressions
in C++
Join at slido.com #lambda
[grcpp]
👍facebook.com/grcpp
👍meetup.com/grcpp-athens
● Knowledge spreading
● Discussions
● Development culture
● Networking
About me
Dimitrios Platis
● Grew up in Rodos, Greece
● Software Engineer @ Zenseact, Sweden
● Course responsible @ DIT112, DAT265
● C++ courses
○ Beginner
○ Advanced
○ Software Design & Architecture
● Interests:
○ Embedded systems
○ Open source software & hardware
○ Robots, Portable gadgets, IoT, 3D printing
● Meetups
○ Embedded@Gothenburg
○ grcpp
● Website: https://platis.solutions
What is your hometown?
ⓘ Start presenting to display the poll results on this slide.
Agenda
● Brief intro
● Basic syntax
● Use cases
⚠ Disclaimers ⚠
- Treat code as pseudocode
- Assuming C++20
- Not (m)any C++20-specific features
demonstrated
- Most, if not everything, should be
C++14 compatible
- Not following any specific coding
guidelines
- Assuming no domain restrictions
- There may be room for optimization
Lambdas - λ
● Unnamed functions, inspired from
functional programming
● May have access to the enclosing
scope
● Unspecified type
● Easy/cheap to create
● Less boilerplate than writing a
function
● "Exotic" syntax
● C++ Lambdas under the hood
auto grcpp = [ ] ( ) { learn_lambdas(); };
grcpp();
[ ] 👉 Capture nothing
( ) 👉 No arguments
{ learn_lambdas(); } 👉 What to do
grcpp() 👉 Invoke lambda
[<capture list>] (<arguments>) -> <return type> {
<function body> }
std::string generation{};
if (yearBorn < 1964)
{
generation = "boomer";
}
else if (yearBorn < 1980)
{
generation = "generation x";
}
else if (yearBorn < 1999)
{
generation = "millenial";
}
else
{
generation = "zoomer";
}
auto getGeneration = [](int yearBorn) -> std::string {
if (yearBorn < 1964)
{
return "boomer";
}
else if (yearBorn < 1980)
{
return "gen x";
}
else if (yearBorn < 1999)
{
return "millenial";
}
return "zoomer";
};
const auto generation = getGeneration(yearBorn);
☝ What are the advantages of this?
Capture by value
auto getGeneration = [yearBorn]() -> std::string
{
if (yearBorn < 1964)
{
return "boomer";
}
else if (yearBorn < 1980)
{
return "generation x";
}
else if (yearBorn < 1999)
{
return "millenial";
}
return "zoomer";
};
const auto generation = getGeneration();
💡 Take yearBorn from the enclosing scope
by copy and use it internally
Capture by reference
💡 Take generation by reference and use it
internally.
std::string generation{};
auto getGeneration = [&generation](int yearBorn) -> void {
if (yearBorn < 1964)
{
generation = "boomer";
}
else if (yearBorn < 1980)
{
generation = "generation x";
}
else if (yearBorn < 1999)
{
generation = "millenial";
}
generation = "zoomer";
};
getGeneration(yearBorn);
Capture clauses
[ ] Capture nothing
[ = ] Capture everything by value
[ & ] Capture everything by reference
[ foo ] Capture foo by value
[ &foo ] Capture foo by reference
[ this ] Capture this (class)
[ =, &foo] Capture everything by value and foo by
reference
[ foo = v[0], &bar = v[1] ] Capture v[0] as foo by value and v[1] as bar
by reference
Trailing return type (optional)
auto getGeneration = [](int yearBorn) {
if (yearBorn < 1964)
{
return "boomer";
}
else if (yearBorn < 1980)
{
return "generation x";
}
else if (yearBorn < 1999)
{
return "millenial";
}
return "zoomer";
};
const auto generation = getGeneration(yearBorn);
⚠ If you omit the return type then its auto
🤔 What is the type of generation?
auto parameters
auto get_first = [](const auto& container) {
return container.at(0);
};
std::vector<int> v{1, 2, 3};
std::array<double, 2> a{5.5, 6.0};
std::cout << get_first(v) << std::endl;
std::cout << get_first(a) << std::endl;
>> 1
>> 5.5
● Avoid repeating redundant types
● Generic lambdas
● C++14 and up
Invoke directly
💡 It may be convenient to invoke a
lambda directly, but consider if this
decreases readability.
const auto generation = [](int yearBorn) -> std::string {
if (yearBorn < 1964)
{
return "boomer";
}
else if (yearBorn < 1980)
{
return "gen x";
}
else if (yearBorn < 1999)
{
return "millenial";
}
return "zoomer";
}(yearBorn);
Under the hood: Functors
class NameGetter
{
public:
NameGetter (int id, std::string& name) : mId{id}, mName{name}
{}
bool operator() (std::map<int, std::string> data)
{
if (!data.contains (mId)) { return false; }
mName = data.at(mId);
return true;
}
private:
int mId;
std::string& mName;
};
NameGetter getNameFunctor{id, name};
auto functorResult = getNameFunctor(data);
auto getNameLambda = [id, &name](auto data) {
if (!data.contains(id))
{
return false;
}
name = data.at(id);
return true;
};
auto lambdaResult = getNameLambda(data);
Full syntax 🚀
● A lot of optional specifiers
○ mutable
○ constexpr
○ throw
○ template parameter types
● Further reading on cppreference
How "strange" do you find
the lambda syntax?
ⓘ Start presenting to display the poll results on this slide.
Compacting complex expressions
● The car should stop moving if a valid sensor measurement
places an obstacle closer than 3 meters
● A measurement is valid if it's larger than 0
if (car.getSpeed() > 0)
{
const auto distance = frontSensor.getDistance();
if (distance > 0 && distance < 3) { car.stop(); }
}
else if (car.getSpeed() < 0)
{
const auto distance = rearSensor.getDistance();
if (distance > 0 && distance < 3) { car.stop(); }
}
auto isObstacle = [](auto distance) {
return distance > 0 && distance < 3;
};
if (car.getSpeed() > 0 &&
isObstacle(frontSensor.getDistance()))
{
car.stop();
}
else if (car.getSpeed() < 0 &&
isObstacle(rearSensor.getDistance()))
{
car.stop();
}
Specializing algorithms
std::for_each(ages.begin(), ages.end(), [](auto age) {
// Do something with age
});
std::map<std::string, int> members{{"John", 31}, {"Jane", 29}, {"Mike", 17}};
auto underage = std::find_if(members.begin(), members.end(), [](auto member)
{
return member.second < 18;
});
if (underage != members.end())
{
std::cout << "Underage member: " << underageMember->first << std::endl;
}
😮 Think lambda whenever you see
Predicate, Function, Deleter etc as
an input!
● std::thread
● std::condition_variable::wait_for
● std::unique_ptr
● …and more
How to pass a lambda - std::function
// class ButtonController
private:
std::map<int, std::function<void(Action)>> listeners_;
public:
void setListener(int buttonId,
std::function<void(Action)> listener)
{
listeners_[buttonId] = listener;
}
void click(int buttonId, Action action)
{
if (listeners_.contains(buttonId))
{
listeners_[buttonId](action);
}
}
auto loggingButtonlistener = [this](Action action) {
switch (action)
{
case Action::MouseDown:
startLogging();
break;
case Action::MouseUp:
stopLogging();
break;
default:
break;
};
};
buttonController_->setListener(loggingButtonId,
loggingButtonlistener);
How to pass a lambda - Templates &
function pointers
Templates
template <typename Function>
void runRepeatedly(Function f)
{
int iteration{ 0 };
while (f(iteration))
{
iteration++;
// Do some more stuff
}
}
Function pointers (capture clause empty)
void runRepeatedly(bool (*f)(int))
{
int iteration{ 0 };
while (f(iteration))
{
iteration++;
// Do some more stuff
}
}
GoogleMock
struct UpdaterMock
{
MOCK_METHOD((bool), update, (std::vector<int>&), ());
};
// With lambdas
std::vector<int> initial{};
EXPECT_CALL(updater, update(_)).WillOnce([&initial](auto& data) {
initial = data;
data.at(0) = 55;
return true;
});
// Without lambdas
EXPECT_CALL(updater, update(_))
.WillOnce(
DoAll(SaveArg<0>(&initial), SetArgReferee<0>(/* ?! */), Return(true)));
● No need to use GMock macros
○ DoAll
○ SaveArg
○ SetArgReferee
○ InvokeWithoutArgs
○ …many more!
● Setting actions to be triggered on
mocked method execution becomes
easier and more readable
Do you have another
use case for lambdas in
mind?
Any questions?
How much did you enjoy
this workshop?
ⓘ Start presenting to display the poll results on this slide.
JetBrains lottery
1 year license for any Jetbrains IDE!
1. Go to: http://plat.is/jetbrains
2. If you won, please stick around until I
contact you
3. If you did not win, better luck next time!
Did you know that as a university student you
can get a free JetBrains license anyway?
Let's keep in
touch!
https://www.linkedin.com/in/
platisd/
dimitris@platis.solutions
@PlatisSolutions

More Related Content

What's hot

What's hot (20)

C Pointers
C PointersC Pointers
C Pointers
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Hibernate
Hibernate Hibernate
Hibernate
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default Methods
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
C Programming : Pointers and Strings
C Programming : Pointers and StringsC Programming : Pointers and Strings
C Programming : Pointers and Strings
 
POINTERS IN C
POINTERS IN CPOINTERS IN C
POINTERS IN C
 
Css Display Property
Css Display PropertyCss Display Property
Css Display Property
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Css colors
Css   colorsCss   colors
Css colors
 
joins in database
 joins in database joins in database
joins in database
 
OOP Core Concept
OOP Core ConceptOOP Core Concept
OOP Core Concept
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 

Similar to Lambda expressions in C++

C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumlercorehard_by
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerSrikanth Shreenivas
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
 
Consider the fork_examplec code under Example code for pr.pdf
Consider the fork_examplec code under Example code for pr.pdfConsider the fork_examplec code under Example code for pr.pdf
Consider the fork_examplec code under Example code for pr.pdfabinayamobiles
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 FeaturesJan Rüegg
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android UpdateGarth Gilmour
 
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...Linaro
 

Similar to Lambda expressions in C++ (20)

Day 1
Day 1Day 1
Day 1
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
Boosting Developer Productivity with Clang
Boosting Developer Productivity with ClangBoosting Developer Productivity with Clang
Boosting Developer Productivity with Clang
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
 
9.C Programming
9.C Programming9.C Programming
9.C Programming
 
C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' Mistakes
 
Consider the fork_examplec code under Example code for pr.pdf
Consider the fork_examplec code under Example code for pr.pdfConsider the fork_examplec code under Example code for pr.pdf
Consider the fork_examplec code under Example code for pr.pdf
 
OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
 
L10
L10L10
L10
 

More from Dimitrios Platis

Interprocess communication with C++.pdf
Interprocess communication with C++.pdfInterprocess communication with C++.pdf
Interprocess communication with C++.pdfDimitrios Platis
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Dimitrios Platis
 
Pointer to implementation idiom
Pointer to implementation idiomPointer to implementation idiom
Pointer to implementation idiomDimitrios Platis
 
Afry software safety ISO26262 (Embedded @ Gothenburg Meetup)
Afry software safety ISO26262 (Embedded @ Gothenburg Meetup)Afry software safety ISO26262 (Embedded @ Gothenburg Meetup)
Afry software safety ISO26262 (Embedded @ Gothenburg Meetup)Dimitrios Platis
 
How to create your own Linux distribution (embedded-gothenburg)
How to create your own Linux distribution (embedded-gothenburg)How to create your own Linux distribution (embedded-gothenburg)
How to create your own Linux distribution (embedded-gothenburg)Dimitrios Platis
 
[grcpp] Refactoring for testability c++
[grcpp] Refactoring for testability c++[grcpp] Refactoring for testability c++
[grcpp] Refactoring for testability c++Dimitrios Platis
 
Refactoring for testability c++
Refactoring for testability c++Refactoring for testability c++
Refactoring for testability c++Dimitrios Platis
 

More from Dimitrios Platis (9)

OpenAI API crash course
OpenAI API crash courseOpenAI API crash course
OpenAI API crash course
 
Interprocess communication with C++.pdf
Interprocess communication with C++.pdfInterprocess communication with C++.pdf
Interprocess communication with C++.pdf
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
 
Introduction to CMake
Introduction to CMakeIntroduction to CMake
Introduction to CMake
 
Pointer to implementation idiom
Pointer to implementation idiomPointer to implementation idiom
Pointer to implementation idiom
 
Afry software safety ISO26262 (Embedded @ Gothenburg Meetup)
Afry software safety ISO26262 (Embedded @ Gothenburg Meetup)Afry software safety ISO26262 (Embedded @ Gothenburg Meetup)
Afry software safety ISO26262 (Embedded @ Gothenburg Meetup)
 
How to create your own Linux distribution (embedded-gothenburg)
How to create your own Linux distribution (embedded-gothenburg)How to create your own Linux distribution (embedded-gothenburg)
How to create your own Linux distribution (embedded-gothenburg)
 
[grcpp] Refactoring for testability c++
[grcpp] Refactoring for testability c++[grcpp] Refactoring for testability c++
[grcpp] Refactoring for testability c++
 
Refactoring for testability c++
Refactoring for testability c++Refactoring for testability c++
Refactoring for testability c++
 

Recently uploaded

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Recently uploaded (20)

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

Lambda expressions in C++

  • 1. Lambda expressions in C++ Join at slido.com #lambda
  • 3. About me Dimitrios Platis ● Grew up in Rodos, Greece ● Software Engineer @ Zenseact, Sweden ● Course responsible @ DIT112, DAT265 ● C++ courses ○ Beginner ○ Advanced ○ Software Design & Architecture ● Interests: ○ Embedded systems ○ Open source software & hardware ○ Robots, Portable gadgets, IoT, 3D printing ● Meetups ○ Embedded@Gothenburg ○ grcpp ● Website: https://platis.solutions
  • 4. What is your hometown? ⓘ Start presenting to display the poll results on this slide.
  • 5. Agenda ● Brief intro ● Basic syntax ● Use cases ⚠ Disclaimers ⚠ - Treat code as pseudocode - Assuming C++20 - Not (m)any C++20-specific features demonstrated - Most, if not everything, should be C++14 compatible - Not following any specific coding guidelines - Assuming no domain restrictions - There may be room for optimization
  • 6. Lambdas - λ ● Unnamed functions, inspired from functional programming ● May have access to the enclosing scope ● Unspecified type ● Easy/cheap to create ● Less boilerplate than writing a function ● "Exotic" syntax ● C++ Lambdas under the hood auto grcpp = [ ] ( ) { learn_lambdas(); }; grcpp(); [ ] 👉 Capture nothing ( ) 👉 No arguments { learn_lambdas(); } 👉 What to do grcpp() 👉 Invoke lambda
  • 7. [<capture list>] (<arguments>) -> <return type> { <function body> } std::string generation{}; if (yearBorn < 1964) { generation = "boomer"; } else if (yearBorn < 1980) { generation = "generation x"; } else if (yearBorn < 1999) { generation = "millenial"; } else { generation = "zoomer"; } auto getGeneration = [](int yearBorn) -> std::string { if (yearBorn < 1964) { return "boomer"; } else if (yearBorn < 1980) { return "gen x"; } else if (yearBorn < 1999) { return "millenial"; } return "zoomer"; }; const auto generation = getGeneration(yearBorn); ☝ What are the advantages of this?
  • 8. Capture by value auto getGeneration = [yearBorn]() -> std::string { if (yearBorn < 1964) { return "boomer"; } else if (yearBorn < 1980) { return "generation x"; } else if (yearBorn < 1999) { return "millenial"; } return "zoomer"; }; const auto generation = getGeneration(); 💡 Take yearBorn from the enclosing scope by copy and use it internally
  • 9. Capture by reference 💡 Take generation by reference and use it internally. std::string generation{}; auto getGeneration = [&generation](int yearBorn) -> void { if (yearBorn < 1964) { generation = "boomer"; } else if (yearBorn < 1980) { generation = "generation x"; } else if (yearBorn < 1999) { generation = "millenial"; } generation = "zoomer"; }; getGeneration(yearBorn);
  • 10. Capture clauses [ ] Capture nothing [ = ] Capture everything by value [ & ] Capture everything by reference [ foo ] Capture foo by value [ &foo ] Capture foo by reference [ this ] Capture this (class) [ =, &foo] Capture everything by value and foo by reference [ foo = v[0], &bar = v[1] ] Capture v[0] as foo by value and v[1] as bar by reference
  • 11. Trailing return type (optional) auto getGeneration = [](int yearBorn) { if (yearBorn < 1964) { return "boomer"; } else if (yearBorn < 1980) { return "generation x"; } else if (yearBorn < 1999) { return "millenial"; } return "zoomer"; }; const auto generation = getGeneration(yearBorn); ⚠ If you omit the return type then its auto 🤔 What is the type of generation?
  • 12. auto parameters auto get_first = [](const auto& container) { return container.at(0); }; std::vector<int> v{1, 2, 3}; std::array<double, 2> a{5.5, 6.0}; std::cout << get_first(v) << std::endl; std::cout << get_first(a) << std::endl; >> 1 >> 5.5 ● Avoid repeating redundant types ● Generic lambdas ● C++14 and up
  • 13. Invoke directly 💡 It may be convenient to invoke a lambda directly, but consider if this decreases readability. const auto generation = [](int yearBorn) -> std::string { if (yearBorn < 1964) { return "boomer"; } else if (yearBorn < 1980) { return "gen x"; } else if (yearBorn < 1999) { return "millenial"; } return "zoomer"; }(yearBorn);
  • 14. Under the hood: Functors class NameGetter { public: NameGetter (int id, std::string& name) : mId{id}, mName{name} {} bool operator() (std::map<int, std::string> data) { if (!data.contains (mId)) { return false; } mName = data.at(mId); return true; } private: int mId; std::string& mName; }; NameGetter getNameFunctor{id, name}; auto functorResult = getNameFunctor(data); auto getNameLambda = [id, &name](auto data) { if (!data.contains(id)) { return false; } name = data.at(id); return true; }; auto lambdaResult = getNameLambda(data);
  • 15. Full syntax 🚀 ● A lot of optional specifiers ○ mutable ○ constexpr ○ throw ○ template parameter types ● Further reading on cppreference
  • 16. How "strange" do you find the lambda syntax? ⓘ Start presenting to display the poll results on this slide.
  • 17. Compacting complex expressions ● The car should stop moving if a valid sensor measurement places an obstacle closer than 3 meters ● A measurement is valid if it's larger than 0 if (car.getSpeed() > 0) { const auto distance = frontSensor.getDistance(); if (distance > 0 && distance < 3) { car.stop(); } } else if (car.getSpeed() < 0) { const auto distance = rearSensor.getDistance(); if (distance > 0 && distance < 3) { car.stop(); } } auto isObstacle = [](auto distance) { return distance > 0 && distance < 3; }; if (car.getSpeed() > 0 && isObstacle(frontSensor.getDistance())) { car.stop(); } else if (car.getSpeed() < 0 && isObstacle(rearSensor.getDistance())) { car.stop(); }
  • 18. Specializing algorithms std::for_each(ages.begin(), ages.end(), [](auto age) { // Do something with age }); std::map<std::string, int> members{{"John", 31}, {"Jane", 29}, {"Mike", 17}}; auto underage = std::find_if(members.begin(), members.end(), [](auto member) { return member.second < 18; }); if (underage != members.end()) { std::cout << "Underage member: " << underageMember->first << std::endl; } 😮 Think lambda whenever you see Predicate, Function, Deleter etc as an input! ● std::thread ● std::condition_variable::wait_for ● std::unique_ptr ● …and more
  • 19. How to pass a lambda - std::function // class ButtonController private: std::map<int, std::function<void(Action)>> listeners_; public: void setListener(int buttonId, std::function<void(Action)> listener) { listeners_[buttonId] = listener; } void click(int buttonId, Action action) { if (listeners_.contains(buttonId)) { listeners_[buttonId](action); } } auto loggingButtonlistener = [this](Action action) { switch (action) { case Action::MouseDown: startLogging(); break; case Action::MouseUp: stopLogging(); break; default: break; }; }; buttonController_->setListener(loggingButtonId, loggingButtonlistener);
  • 20. How to pass a lambda - Templates & function pointers Templates template <typename Function> void runRepeatedly(Function f) { int iteration{ 0 }; while (f(iteration)) { iteration++; // Do some more stuff } } Function pointers (capture clause empty) void runRepeatedly(bool (*f)(int)) { int iteration{ 0 }; while (f(iteration)) { iteration++; // Do some more stuff } }
  • 21. GoogleMock struct UpdaterMock { MOCK_METHOD((bool), update, (std::vector<int>&), ()); }; // With lambdas std::vector<int> initial{}; EXPECT_CALL(updater, update(_)).WillOnce([&initial](auto& data) { initial = data; data.at(0) = 55; return true; }); // Without lambdas EXPECT_CALL(updater, update(_)) .WillOnce( DoAll(SaveArg<0>(&initial), SetArgReferee<0>(/* ?! */), Return(true))); ● No need to use GMock macros ○ DoAll ○ SaveArg ○ SetArgReferee ○ InvokeWithoutArgs ○ …many more! ● Setting actions to be triggered on mocked method execution becomes easier and more readable
  • 22. Do you have another use case for lambdas in mind? Any questions?
  • 23. How much did you enjoy this workshop? ⓘ Start presenting to display the poll results on this slide.
  • 24. JetBrains lottery 1 year license for any Jetbrains IDE! 1. Go to: http://plat.is/jetbrains 2. If you won, please stick around until I contact you 3. If you did not win, better luck next time! Did you know that as a university student you can get a free JetBrains license anyway?