Skip to content

Instantly share code, notes, and snippets.

@codehz
Created August 5, 2016 04:13
Show Gist options
  • Save codehz/6715390440ca38eadba812de4de7b7ca to your computer and use it in GitHub Desktop.
Save codehz/6715390440ca38eadba812de4de7b7ca to your computer and use it in GitHub Desktop.
#include <iostream>
template<typename Target, typename Source>
struct force_cast {
union {
Source source;
Target target;
};
force_cast(Source source) : source(source) {};
operator Target() {
return target;
}
};
template<typename Class, typename Ret, typename... Args>
Ret(*make_callback(Ret(Class::*source)(Args...)))(void *, Args...) {
return force_cast<Ret(*)(void *, Args...), Ret(Class::*)(Args...)>(source);
}
using wanted_function = void(*)(void *self, int a);
void test_callback(wanted_function cb, void *self) {
cb(self, 5);
}
class TestClass {
void onEvent(int a) {
std::cout << "a=" << a << std::endl;
}
public:
TestClass() {
test_callback(make_callback(TestClass::onEvent), this);
}
};
int main() {
TestClass test;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment