클래스 멤버 함수 포인터 바인드
여러 클래스의 멤버 함수 포인터를 하나의 vector 에 보관 및 사용
함수 Container 클래스
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
class FunctionContainer
{
public:
template <typename T>
void AddFunc(void (T::*function)(void*, int), T *object)
{
typedef std::tuple<void (T::*)(void*, int), T *> CallbackType;
func_pointer func = {FuncWrapper<T>, new CallbackType(function, object)};
m_func_list.push_back(func);
}
void RunFunc(void *data, int len)
{
for (auto iter = m_func_list.begin(); iter != m_func_list.end(); ++iter)
{
iter->func(iter->type, data, len);
}
}
private:
template <typename T>
static void FuncWrapper(void *type, void *data, int len)
{
typedef std::tuple<void (T::*)(void*, int), T *> CallbackType;
CallbackType *p = (CallbackType*)type;
void (T::*function)(void*, int) = std::get<0>(*p);
T *object = std::get<1>(*p);
(object->*function)(data, len);
}
typedef struct
{
void (*func)(void*, void*, int);
void *type;
}func_pointer;
std::vector<func_pointer> m_evt_func_list;
}
사용
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
class AAA
{
public:
AAA()
{
m_int = 100;
};
virtual ~AAA() {};
void Function1(void *data, int len)
{
printf ("%d\n", m_int++);
}
void Function2(void *data, int len)
{
printf ("%d\n", m_int++);
}
int m_int;
};
class BBB
{
public:
BBB()
{
m_int = 500;
};
virtual ~BBB() {};
void Function1(void *data, int len)
{
printf ("%d\n", m_int++);
}
void Function2(void *data, int len)
{
printf ("%d\n", m_int++);
}
int m_int;
};
int main(int argc, const char * const * argv)
{
FunctionContainer cont;
AAA a;
BBB b;
cont.AddFunc(&AAA::Function1, &a);
cont.AddFunc(&AAA::Function2, &a);
cont.AddFunc(&BBB::Function1, &b);
cont.AddFunc(&BBB::Function2, &b);
cont.RunFunc(NULL, 10);
return 0;
}