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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
|
-
-
|
!
-
|
-
!
|
|
-
!
|
|
-
!
|
!
|
-
|
!
|
-
|
!
|
-
|
!
|
-
|
!
-
|
-
!
|
-
|
|
!
|
-
!
|
-
|
!
|
-
!
|
-
|
|
|
|
|
|
!
|
-
!
-
|
-
|
!
!
|
-
!
-
|
-
|
|
!
!
|
-
!
|
-
!
|
-
!
|
|
-
!
|
-
!
|
-
!
-
|
!
|
-
!
|
-
-
!
|
-
!
!
|
-
!
-
-
!
!
|
|
-
!
|
-
|
!
|
-
!
|
-
|
!
|
-
!
|
-
|
!
|
|
|
!
!
-
|
!
-
|
|
-
!
|
|
-
!
|
|
-
!
|
|
|
!
| #include <functional>
#include <string>
#include <memory>
#include <iostream>
namespace
{
class Character
{
protected:
Character() { }
public:
virtual ~Character() { }
private:
Character(const Character&);
void operator=(const Character&);
};
class Suika : public Character { };
class Meiling : public Character { };
class Tenshi : public Character { };
class Controller
{
private:
template<class TMemFunc, class TChara>
void invokeCall(void* memFunc, void* chara)
{
TMemFunc* f = static_cast<TMemFunc*>(memFunc);
(*f)(this, static_cast<TChara*>(chara));
}
template<class TMemFunc>
void invokeDispose(void* memFunc)
{
delete static_cast<TMemFunc*>(memFunc);
}
template<class TChara>
void setFunc(void (Controller::*func)(TChara*))
{
resetFunc();
typedef std::mem_fun1_t<void, Controller, TChara*> MemFuncType;
_memFunc = new MemFuncType(func);
_invokeCall = &Controller::invokeCall<MemFuncType, TChara>;
_invokeDispose = &Controller::invokeDispose<MemFuncType>;
}
void doFunc()
{
if (_memFunc != 0)
{
(this->*_invokeCall)(_memFunc, _chara.get());
}
}
void resetFunc()
{
if (_memFunc != 0)
{
(this->*_invokeDispose)(_memFunc);
_memFunc = 0;
}
}
void* _memFunc;
void (Controller::*_invokeCall)(void*, void*);
void (Controller::*_invokeDispose)(void*);
public:
Controller()
: _chara(), _memFunc(0), _invokeCall(0), _invokeDispose(0)
{
}
virtual ~Controller()
{
resetFunc();
}
template<class TChara>
void initialize()
{
setFunc(&Controller::procCallback<TChara>);
_chara.reset(new TChara());
}
void execute()
{
doFunc();
}
private:
template<class TChara>
void procCallback(TChara*)
{
std::cout << "(Basic function)" << std::endl;
}
template<>
void procCallback(Suika*)
{
std::cout << "Ibuki Suika" << std::endl;
}
template<>
void procCallback(Meiling*)
{
std::cout << "Chugo... Hong-Meiling!!" << std::endl;
}
private:
std::auto_ptr<Character> _chara;
};
}
int main(int, char**)
{
Controller ctrl;
ctrl.initialize<Suika>();
ctrl.execute();
ctrl.initialize<Meiling>();
ctrl.execute();
ctrl.initialize<Tenshi>();
ctrl.execute();
return 0;
}
|