First of all, you should read the lambda expression’s reference.
Lambda is a function
-
different format, but the same.
auto f1 = [](int i)->void { printf("%dn", i); }; void f2(int i) { printf("%dn", i); } f1(1); f2(1);
as a caller, f1 is the same with f2
-
advantage: convenient
- fastly define a simple function
int main() { auto foo_min = [](int a, int b) -> int { return a < b ? a : b; }; auto m = foo_min(1, 2); }
- callback
int do_read(..., int(*on_read)(const char* buf, int len)) { ... } do_read(..., [](const char* buf, int len)->int{ // handle buf ... });
Lambda is more than a function
-
lambda is a closure. what is a closure?
a closure is a record storing a function together with an environment:
reference from wikipedia
-
example for closure
auto foo(int i) { return [i](int n)->void { printf("%dn", i + n); }; } auto f1 = foo(1); auto f2 = foo(2); f1(1); f2(1);
-
how about lambda meets c-style function type?
-
capture nothing
typedef void (*func_t)(); auto f = []()->void { printf("hellon"); };
f CAN be converted to func_t
-
capture something
typedef void (*func_t)(); int i = 5; auto f = [i]()->void { printf("%dn", i); };
f CAN NOT be converted to func_t, because this lambda involves a closure that func_t CAN NOT express.
-
-
what’s the type?
speaking in code …
typedef std::function<void(int)> the_type; std::vector<the_type> funcs; for(int i = 0; i < 5; ++i) { funcs.push_back([i](int n)->void{ printf("%dn", i + n); }); } for (auto f : funcs) { f(10); }
output
10 11 12 13 14
近期评论