1 |
/* |
2 |
callback.h -- C++ callback mechanism |
3 |
Copyright (C) 2003-2018 Marc Lehmann <pcg@goof.com> |
4 |
|
5 |
Deliantra is free software; you can redistribute it and/or modify |
6 |
it under the terms of the GNU General Public License as published by |
7 |
the Free Software Foundation; either version 2 of the License, or |
8 |
(at your option) any later version. |
9 |
|
10 |
This program is distributed in the hope that it will be useful, |
11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
13 |
GNU General Public License for more details. |
14 |
|
15 |
You should have received a copy of the GNU General Public License |
16 |
along with gvpe; if not, write to the Free Software |
17 |
Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
18 |
*/ |
19 |
|
20 |
#ifndef CALLBACK_H__ |
21 |
#define CALLBACK_H__ |
22 |
|
23 |
template<typename signature> |
24 |
class callback; |
25 |
|
26 |
template<typename R, typename ...Args> |
27 |
class callback<R (Args...)> |
28 |
{ |
29 |
struct object { }; |
30 |
|
31 |
typedef R (object::*ptr_type)(Args...); |
32 |
|
33 |
void *obj; |
34 |
R (object::*meth)(Args...); |
35 |
|
36 |
/* a proxy is a kind of recipe on how to call a specific class method */ |
37 |
struct proxy_base { |
38 |
virtual R call (void *obj, R (object::*meth)(Args...), Args... args) const = 0; |
39 |
}; |
40 |
template<class O1, class O2> |
41 |
struct proxy : proxy_base { |
42 |
virtual R call (void *obj, R (object::*meth)(Args...), Args... args) const |
43 |
{ |
44 |
return (R)((reinterpret_cast<O1 *>(obj)) ->* (reinterpret_cast<R (O2::*)(Args...)>(meth))) |
45 |
(args...); |
46 |
} |
47 |
}; |
48 |
|
49 |
proxy_base *prxy; |
50 |
|
51 |
public: |
52 |
template<class O1, class O2> |
53 |
explicit callback (O1 *object, R (O2::*method)(Args...)) |
54 |
{ |
55 |
static proxy<O1,O2> p; |
56 |
obj = reinterpret_cast<void *>(object); |
57 |
meth = reinterpret_cast<R (object::*)(Args...)>(method); |
58 |
prxy = &p; |
59 |
} |
60 |
|
61 |
R call(Args... args) const |
62 |
{ |
63 |
return prxy->call (obj, meth, args...); |
64 |
} |
65 |
|
66 |
R operator ()(Args... args) const |
67 |
{ |
68 |
return call (args...); |
69 |
} |
70 |
}; |
71 |
|
72 |
#endif |