-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathLambda02.cpp
More file actions
55 lines (40 loc) · 1.27 KB
/
Lambda02.cpp
File metadata and controls
55 lines (40 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// =====================================================================================
// Lambda02.cpp // Lambdas under the Hood
// =====================================================================================
module modern_cpp:lambda;
namespace LambdasUnderTheHood {
static void test_01()
{
int n{ 10 };
auto lambda{ [n](int a) { return n + a; } };
auto m { lambda(20) }; // m is now 30
std::cout << "m: " << m << std::endl;
}
static void test_02()
{
class LambdaClass
{
public:
LambdaClass(int n) : m_n{ n } {}
int operator() (int a) const
{
return m_n + a;
}
private:
mutable int m_n; // if lambda modifies state, add keyword 'mutable'
};
const int n{ 30 };
auto lambda{ LambdaClass(n) };
auto m{ lambda(20) }; // m is now 50
std::cout << "m: " << m << std::endl;
}
}
void main_lambda_and_closure()
{
using namespace LambdasUnderTheHood;
test_01();
test_02();
}
// =====================================================================================
// End-of-File
// =====================================================================================