Last active
August 29, 2015 14:07
-
-
Save rcc/7512c61ba3d2031e77ae to your computer and use it in GitHub Desktop.
C++ Templated Bounce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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