forked from chronolaw/boost_guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction1.cpp
More file actions
123 lines (89 loc) · 1.91 KB
/
Copy pathfunction1.cpp
File metadata and controls
123 lines (89 loc) · 1.91 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Copyright (c) 2015
// Author: Chrono Law
#include <std.hpp>
//using namespace std;
#include <boost/bind.hpp>
#include <boost/function.hpp>
using namespace boost;
//////////////////////////////////////////
void case1()
{
function<int()> func, func1;
function<int (int , int , int )> func2;
//func == func1;
assert(func.empty());
assert(!func);
function0<int> func0;
func0.clear();
assert(!func0);
}
//////////////////////////////////////////
int f(int a, int b)
{ return a + b;}
void case2()
{
//function<int(int,int)> func;
function<decltype(f)> func;
assert(!func);
func = f;
assert(func.contains(&f));
if (func)
{
std::cout << func(10, 20);
}
func = 0;
assert(func.empty());
}
//////////////////////////////////////////
struct demo_class
{
int add(int a, int b)
{ return a + b; }
int operator()(int x) const
{ return x*x; }
};
void case3()
{
function<int(demo_class&, int,int)> func1;
func1 = bind(&demo_class::add, _1, _2, _3);
demo_class sc;
std::cout << func1(sc, 10, 20);
function<int(int,int)> func2;
func2 = bind(&demo_class::add,&sc, _1, _2);
std::cout << func2(10, 20);
}
//////////////////////////////////////////
void case4()
{
demo_class sc;
function<int(int)> func;
func = cref(sc);
std::cout << func(10);
}
//////////////////////////////////////////
template<typename T>
struct summary
{
typedef void result_type;
T sum;
summary(T v = T()):sum(v){}
void operator()(T const &x)
{ sum += x; }
};
void case5()
{
std::vector<int> v = {1,3,5,7,9};
summary<int> s;
function<void(int const&)> func(ref(s));
std::for_each(v.begin(), v.end(), func);
std::cout << s.sum << std::endl;
}
//////////////////////////////////////////
int main()
{
case1();
case2();
case3();
case4();
case5();
}