forked from czyt1988/czyBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
95 lines (75 loc) · 1.64 KB
/
main.cpp
File metadata and controls
95 lines (75 loc) · 1.64 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <functional>
#include <vector>
#include <memory>
#include <algorithm>
#define SHOW_TRAP_1 1
#define SHOW_TRAP_2 1
typedef std::function<void()> FP;
class Point
{
public:
Point(int x,int y):m_x(x),m_y(y)
{
}
void print()
{
#if 1
int x = m_x;
int y = m_y;
s_print_history.push_back([x,y](){std::cout << "(X:" << x << ",Y:" << y <<")" << std::endl;});
#else
s_print_history.push_back([=](){std::cout << "(X:" << m_x << ",Y:" << m_y <<")" << std::endl;});
#endif
std::cout << "(X:" << m_x << ",Y:" << m_y <<")" << std::endl;
}
static void print_history()
{
std::cout << "print history:"<<std::endl;
std::for_each(s_print_history.begin(),s_print_history.end(),[](FP p){
if(p)
p();
});
}
private:
int m_x;
int m_y;
typedef std::function<void(void)> FP;
static std::vector<FP> s_print_history;
};
std::vector<FP> Point::s_print_history = std::vector<FP>();
void run_fun_ptr(FP fp);
FP get_fun_ptr();
FP get_fun_ptr_ref();
int main()
{
#if SHOW_TRAP_1
run_fun_ptr(get_fun_ptr());
run_fun_ptr(get_fun_ptr_ref());
#endif
#if SHOW_TRAP_2
std::unique_ptr<Point> p;
p.reset(new Point(1,1));p->print();
p.reset(new Point(2,2));p->print();
p.reset(new Point(3,3));p->print();
Point::print_history();
#endif
return 0;
}
void run_fun_ptr(FP fp)
{
if(fp)
{
fp();
}
}
FP get_fun_ptr()
{
int a = 2;
return [=](){std::cout << "= a:"<<a << std::endl;};
}
FP get_fun_ptr_ref()
{
int a = 2;
return [&](){std::cout << "& a:"<<a << std::endl;};
}