/* callback.h -- C++ callback mechanism Copyright (C) 2003-2018 Marc Lehmann Deliantra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with gvpe; if not, write to the Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CALLBACK_H__ #define CALLBACK_H__ template class callback; template class callback { struct object { }; typedef R (object::*ptr_type)(Args...); void *obj; R (object::*meth)(Args...); /* a proxy is a kind of recipe on how to call a specific class method */ struct proxy_base { virtual R call (void *obj, R (object::*meth)(Args...), Args... args) const = 0; }; template struct proxy : proxy_base { virtual R call (void *obj, R (object::*meth)(Args...), Args... args) const { return (R)((reinterpret_cast(obj)) ->* (reinterpret_cast(meth))) (args...); } }; proxy_base *prxy; public: template explicit callback (O1 *object, R (O2::*method)(Args...)) { static proxy p; obj = reinterpret_cast(object); meth = reinterpret_cast(method); prxy = &p; } R call(Args... args) const { return prxy->call (obj, meth, args...); } R operator ()(Args... args) const { return call (args...); } }; #endif