-
Notifications
You must be signed in to change notification settings - Fork 0
/
function_call.cpp
130 lines (114 loc) · 1.92 KB
/
function_call.cpp
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
122
123
124
125
126
127
128
129
130
//
// 指定メソッド呼び出しテスト
//
// Y.Suzuki
//
#include <iostream>
#include <list>
#include "test.hpp"
Test::Dump dump;
//
struct Context
{
int phase;
int count;
};
// listener base
class ListenerBase
{
public:
virtual void callFunc(Context*) = 0;
};
// template Listener
template <class T, class Tc>
class Listener : public ListenerBase
{
T* obj;
void (T::*func)(Tc*);
public:
Listener(T* o, void (T::*f)(Tc*))
{
obj = o;
func = f;
}
void callFunc(Tc* c) { (obj->*func)(c); }
};
// function list
class FunctionList
{
std::list<ListenerBase*> l;
public:
template <class T>
void push(T* o, void (T::*f)(Context*))
{
l.push_back(new Listener<T, Context>(o, f));
}
void call(Context* c)
{
std::list<ListenerBase*>::iterator li = l.begin();
while (li != l.end())
{
ListenerBase* lb = *li;
lb->callFunc(c);
li++;
}
}
};
//
// main method
//
using namespace std;
// local classes
class HexDisp
{
int num;
public:
HexDisp(int n) : num(n) {}
void disp(Context* ctx) { cout << hex << (num + ctx->count) << endl; }
};
class DecDisp
{
int num;
public:
DecDisp(int n) : num(n) {}
void disp(Context* ctx) { cout << dec << (num + ctx->count) << endl; }
};
class PhaseDisp
{
public:
PhaseDisp() {}
void disp(Context* ctx)
{
if (ctx->phase == 0)
dump.put("Start!");
else if (ctx->phase == 2)
{
dump.put("Finish!");
}
}
};
//
// start up routine
//
int
main(int argc, char* argv[])
{
FunctionList fl;
dump.put("setup");
HexDisp h(1234);
DecDisp d(0x2323);
PhaseDisp p;
fl.push(&p, &PhaseDisp::disp);
fl.push(&h, &HexDisp::disp);
fl.push(&d, &DecDisp::disp);
// 10回登録メソッドを呼び出してみる
for (int cnt = 0; cnt <= 10; cnt++)
{
Context ctx;
ctx.phase = (cnt == 0) ? 0 : (cnt == 10) ? 2 : 1;
ctx.count = cnt;
fl.call(&ctx);
}
dump.put("done");
}
// End