fork download
  1. #include <iostream>
  2.  
  3. void register_callback(void* f, void* data);
  4. void invoke_callback();
  5.  
  6. template <typename T>
  7. void my_callback(void* data) {
  8. T& x = *static_cast<T*>(data);
  9. std:: cout << "Call[T] with " << x << std::endl;
  10. }
  11.  
  12. // Explicit instantiation:
  13. //template void my_callback<int>(void* data);
  14.  
  15. template <typename T>
  16. void do_register_callback(T& value) {
  17. // Implicit instantiation:
  18. if (false) { my_callback<T>(0); }
  19. register_callback(reinterpret_cast<void*>(static_cast<void(*)(void*)>(my_callback<T>)), &value);
  20. }
  21.  
  22. int main() {
  23. int ft = 42;
  24. do_register_callback(ft);
  25. invoke_callback();
  26. }
  27.  
  28. // [ Library ] /////////////////////////////////////////////////////////////////
  29.  
  30. struct callback_t {
  31. void (*f)(void*);
  32. void* data;
  33. } library_callback_data;
  34.  
  35. void register_callback(void* f, void* data) {
  36. library_callback_data.f = reinterpret_cast<void(*)(void*)>(f);
  37. library_callback_data.data = data;
  38. }
  39.  
  40. void invoke_callback() {
  41. (*library_callback_data.f)(library_callback_data.data);
  42. }
Success #stdin #stdout 0s 2724KB
stdin
Standard input is empty
stdout
Call[T] with 42