You are on page 1of 2

=====================

Lambda Expressions [ FOCUS MORE ON LAMDA FUNCTIONS ]


=====================

Anonymous function can be created in C++ 11, and it's known as Lambda function.
So basically lambda expression allows us to define functions locally. Also,
it allows to define function at the place of the call, hence eliminating much of
the complexity and security risks.

form:
[capture](parameters)->return-type {body}
[&]{}; // OK: by-reference capture default
[&, i]{}; // OK: by-reference capture, except i is captured by copy
[&, &i] {}; // Error: by-reference capture when by-reference is the default
[&, this] {}; // OK, equivalent to [&]
[&, this, i]{}; // OK, equivalent to [&, i]
[&, i]{}; // OK
[&, &i]{}; // ERROR: i preceded by & when & is the default
[=, this]{}; // ERROR: this when = is the default
[=, *this]{ }; // OK: captures this by value. See below.
[i, i]{}; // ERROR: i repeated
Note: An identifier or this can't appear more than once in a capture clause
If a capture clause includes a capture-default &, then no identifier in a
capture of that capture clause can have the form &identifier.
Likewise, if the capture clause includes a capture-default =, then no
capture of that capture clause can have the form =identifier.
An identifier or this can't appear more than once in a capture clause.
The following code snippet illustrates some examples:

lamda with variodic template


template<class... Args>
void f(Args... args) {
auto x = [args...] { return g(args...); };
x();
}

use case:

for_each( x.begin() ; x.end() ; [ this , &y ] ( type of x )->void { } )

why we interduce this ?

Risks:
- A lambda can only capture local variables. When a lambda is defined within a
member function, you may believe that you are capturing a member
variable of the current class, but in fact, what you are capturing is this.
This may be very surprising, and lead to bugs if the lambda is then used after
the current object has been destroyed. [Found same kind of issue in AvahiImpl ]

=====================================
https://github.com/AnthonyCalandra/modern-cpp-features/blob/master/CPP11.md
=====================================
std::begin/end
=====================================
std::begin and std::end free functions were added to return begin and end iterators
of a container generically. These functions also work with raw arrays which do not
have begin and end member functions.
template <typename T>
int CountTwos(const T& container) {
return std::count_if(std::begin(container), std::end(container), [](int item) {
return item == 2;
});
}

std::vector<int> vec = {2, 2, 43, 435, 4543, 534};


int arr[8] = {2, 43, 45, 435, 32, 32, 32, 32};
auto a = CountTwos(vec); // 2
auto b = CountTwos(arr); // 1

You might also like