Created
August 5, 2016 04:13
-
-
Save codehz/6715390440ca38eadba812de4de7b7ca to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <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