-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
65 lines (52 loc) · 1.28 KB
/
main.cpp
File metadata and controls
65 lines (52 loc) · 1.28 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
56
57
58
59
60
61
62
63
64
65
#include <functional>
#include <iostream>
// std::function绑定带捕获的lambda和不带捕获的lambda
void test1()
{
// 不带捕获的lambda
std::function<int(int, int)> f = [](int a, int b)
{ return a + b; };
std::cout << f(1, 2) << '\n'
<< '\n';
// 带捕获的lambda
int num = 1;
int num2 = 1;
std::cout << "num2: " << num << '\n';
std::function<int(int, int)> f2 = [=, &num2](int a, int b)
{
num2 = 2;
std::cout << "num: " << num << '\n';
return a + b;
};
std::cout << f2(1, 2) << '\n';
std::cout << "num2: " << num2 << '\n';
}
int add(int a, int b) { return a + b; }
// std::function绑定普通函数
void test2()
{
std::function<int(int, int)> f = add;
std::cout << f(1, 2) << '\n';
}
// std::function绑定成员函数
class Math
{
public:
int add2(int a, int b) { return a + b; }
};
void test3()
{
Math m;
// 这个写法比较特殊
std::function<int(int, int)> f = std::bind(&Math::add2, &m, std::placeholders::_1, std::placeholders::_2);
std::cout << f(1, 2) << '\n';
}
int main()
{
test1();
std::cout << "-------------------------------" << '\n';
test2();
std::cout << "-------------------------------" << '\n';
test3();
return 0;
}