#include <iostream> #include <thread> int main() { std::thread t1([] { std::cout << "Hello World" << std::endl; }); t1.join(); return 0; }
A lambda closure is nothing but a variable storing a lambda expression.
You can store a lambda in a closure if you intend to reuse the lambda expression at more than one place in your code.
#include <iostream> #include <thread> int main() { // Define a lambda closure. auto HelloWorldFunc = []() -> void { std::cout << "Hello World" << std::endl; }; std::thread t1(HelloWorldFunc); t1.join(); return 0; }
auto HelloWorldFunc = [](std::string name, int age) -> void { std::cout << "Hello " << name << ". You are " << age << " years old." << std::endl; }; std::thread t1(HelloWorldFunc, "Peter", 21); t1.join();