fork download
  1. #include <iostream>
  2.  
  3. template<class T>using type=T;
  4. template<class F>
  5. struct callback_t;
  6.  
  7. template<class F, class Sig>
  8. struct cast_helper_pvoid_last;
  9. template<class F, class R, class... Args>
  10. struct cast_helper_pvoid_last<F, R(Args...)> {
  11. type<R(*)(Args..., void*)> operator()() const {
  12. return [](Args... args, void* pvoid)->R {
  13. auto* callback = static_cast<callback_t<F>*>(pvoid);
  14. return callback->f( std::forward<Args>(args)... );
  15. };
  16. }
  17. };
  18.  
  19. template<class F>
  20. struct callback_t {
  21. F f;
  22. void* pvoid() { return this; }
  23.  
  24. template<class Sig>
  25. auto pvoid_at_end()->decltype( cast_helper_pvoid_last<F, Sig>{}() ) {
  26. return cast_helper_pvoid_last<F,Sig>{}();
  27. }
  28. };
  29. template<class T>using decay_t=typename std::decay<T>::type;
  30. template<class F>
  31. callback_t<decay_t<F>> make_callback( F&& f ) { return {std::forward<F>(f)}; }
  32.  
  33. int main() {
  34. int x = 3;
  35. auto callback = make_callback( [&]( int y ) { return x+y; } );
  36. int (*func)(int, void*) = callback.pvoid_at_end<int(int)>();
  37. std::cout << func( 1, callback.pvoid() ) << "\n";
  38. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
4