-
Notifications
You must be signed in to change notification settings - Fork 1
/
methodcallback.h
96 lines (77 loc) · 2.31 KB
/
methodcallback.h
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
#ifndef JWUTIL_METHODCALLBACK_H
#define JWUTIL_METHODCALLBACK_H
#include <assert.h>
#include <utility>
namespace jw_util
{
template <typename... ArgTypes>
class MethodCallback
{
public:
MethodCallback()
: stub_ptr(0)
{}
static MethodCallback<ArgTypes...> create_dummy()
{
return MethodCallback(static_cast<void*>(0), &dummy_stub);
}
template <void (*Function)(ArgTypes...)>
static MethodCallback<ArgTypes...> create()
{
return MethodCallback(static_cast<void*>(0), &function_stub<Function>);
}
template <typename ClassType, void (ClassType::*Method)(ArgTypes...)>
static MethodCallback<ArgTypes...> create(ClassType *inst)
{
return MethodCallback(static_cast<void*>(inst), &method_stub<ClassType, Method>);
}
bool is_valid() const
{
return stub_ptr;
}
void call(ArgTypes... args) const
{
assert(stub_ptr);
(*stub_ptr)(inst_ptr, std::forward<ArgTypes>(args)...);
}
template <typename ClassType>
ClassType *get_inst() const
{
return static_cast<ClassType *>(inst_ptr);
}
bool is_same_method(const MethodCallback<ArgTypes...> &other) const
{
return stub_ptr == other.stub_ptr;
}
bool operator==(const MethodCallback<ArgTypes...> &other) const
{
return inst_ptr == other.inst_ptr && stub_ptr == other.stub_ptr;
}
bool operator!=(const MethodCallback<ArgTypes...> &other) const
{
return inst_ptr != other.inst_ptr || stub_ptr != other.stub_ptr;
}
private:
typedef void (*StubType)(void *inst_ptr, ArgTypes...);
MethodCallback(void *inst_ptr, StubType stub_ptr)
: inst_ptr(inst_ptr)
, stub_ptr(stub_ptr)
{}
static void dummy_stub(void *, ArgTypes...) {}
template <void (*Function)(ArgTypes...)>
static void function_stub(void *inst_ptr, ArgTypes... args)
{
(void) inst_ptr;
(*Function)(std::forward<ArgTypes>(args)...);
}
template <class ClassType, void (ClassType::*Method)(ArgTypes...)>
static void method_stub(void *inst_ptr, ArgTypes... args)
{
ClassType* inst = static_cast<ClassType *>(inst_ptr);
(inst->*Method)(std::forward<ArgTypes>(args)...);
}
void *inst_ptr;
StubType stub_ptr;
};
}
#endif // JWUTIL_METHODCALLBACK_H