Skip to content

Instantly share code, notes, and snippets.

@rcc
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcc/7512c61ba3d2031e77ae to your computer and use it in GitHub Desktop.
Save rcc/7512c61ba3d2031e77ae to your computer and use it in GitHub Desktop.
C++ Templated Bounce
#include <stdio.h>
class Foo {
public:
Foo(int val) : val_(val) { }
void operator()(int v) const
{
printf("%p : val = %d\n", this, val_ + v);
}
private:
int val_;
};
// Callback bounce function
template<class T, class Ret, class ...Args>
Ret bounce(void *priv, Args... args)
{
return (*reinterpret_cast<T *>(priv))(args...);
}
// Callback simulator
void call_callback(void (*func)(void *, int), void *priv, int v)
{
if (func) {
func(priv, v);
}
}
// Main Entry
int main()
{
Foo bar(1327);
call_callback(&bounce<Foo>, &bar, 10);
return 0;
}
// unused method_caller template. example of deducing method pointer traits from arguments.
template<class T, class Ret, class ...Args>
inline Ret method_caller(T *inst, Ret (T::*method)(Args...), Args... args)
{
return ((*inst).*method)(args...);
}
template<class T, class Ret, class ...Args>
inline Ret method_caller(T *inst, Ret (T::*method)(Args...) const, Args... args)
{
return ((*inst).*method)(args...);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment