So you wanna use lambdas in C++ huh? It's as simple as that:
auto lambda = []() = {
printf("Hello, I am a simplest lambda.");
};
Now, if you wanna invoke it only once you can omit assigning value and either add parentheses at the end or use std::invoke():
[]() = {
printf("Hello, I am a simplest lambda.");
}();
std::invoke([]() {
printf("Hello, I am a simplest lambda.");
});
Or if you got a value you can just call it like any other function:
lambda();
What about parameters, return value? Just put them where they belong:
auto lambda = [](int a, int b) {
return a + b;
};
int result = lambda(1, 2);
Guess we are done here, let's move on and talk about captures. Ok, see those square brackets over there? That's called Capture List, a place where you put your captures. A capture is an identifier of a variable defined outside your lambda and a method to copy(capture) it.
[] - empty brackets mean there is nothing to capture.
[count] - identifier means capturing a variable by value.
int count = 9;
auto lambda = [count]() {
std::cout << count << std::endl;
};
[&count] - identifier with ampersand means capturing a variable by reference.
auto lambda = [&count]() {
std::cout << count << std::endl;
};
[=] - means capturing all local variables used inside lambda by value.
void function()
{
int count = 9;
auto lambda = [=]() {
std::cout << count << std::endl;
};
lambda();
}
[&] - means capturing all local variables used inside lambda by reference.
void function()
{
int count = 9;
auto lambda = [&]() {
std::cout << count << std::endl;
};
lambda();
}
[this] - means capturing this pointer.
class ClassWithLambda
{
private:
int count;
public:
ClassWithLambda():count(9) {}
void methodWithLambda()
{
auto lambda = [this]() {
std::cout << count << std::endl;
};
lambda();
}
};
Actually [=] and [&] capture this pointer too, if it exists:
class ClassWithLambda
{
private:
int count;
public:
ClassWithLambda():count(9) {}
void methodWithLambda()
{
auto lambda = [=]() {
std::cout << count << std::endl;
};
lambda();
}
};
class ClassWithLambda
{
private:
int count;
public:
ClassWithLambda():count(9) {}
void methodWithLambda()
{
auto lambda = [&]() {
std::cout << count << std::endl;
};
lambda();
}
};
No comments:
Post a Comment