fork download
  1. #include <utility>
  2. #include <iostream>
  3. #include <tuple>
  4.  
  5.  
  6. template<int...> struct seq {};
  7. template<int Min, int Max, int... s> struct make_seq:make_seq<Min, Max-1, Max-1, s...> {};
  8. template<int Min, int... s> struct make_seq<Min, Min, s...> {
  9. typedef seq<s...> type;
  10. };
  11. template<int Max, int Min=1>
  12. using MakeSeq = typename make_seq<Min, Max>::type;
  13.  
  14. template<typename Func, typename Tuple, int... s>
  15. void do_call( Func&& f, seq<s...>, Tuple&& tup ) {
  16. std::forward<Func>(f)( std::get<s>(std::forward<Tuple>(tup))... );
  17. }
  18.  
  19. typedef void(*pvoidary)(void*);
  20.  
  21. template<typename Lambda>
  22. struct pvoidary_factory {
  23. Lambda func;
  24. pvoidary_factory( Lambda const& f ):func(f) {}
  25. pvoidary_factory( pvoidary_factory const& ) = default;
  26. pvoidary_factory( pvoidary_factory && ) = default;
  27. template<typename... Args>
  28. std::tuple<pvoidary, void*> operator()(Args&&... args) const {
  29. typedef std::tuple<Lambda, Args...> package;
  30. void* pVoid = new package(func, std::forward<Args>(args)...);
  31. return std::make_tuple(
  32. [](void* pVoid) {
  33. package* pPack = reinterpret_cast<package*>(pVoid);
  34. do_call( std::get<0>(*pPack), MakeSeq<sizeof...(Args)+1, 1>(), *pPack );
  35. },
  36. pVoid
  37. );
  38. }
  39. };
  40. template<typename Lambda>
  41. pvoidary_factory<Lambda> Wrap( Lambda const& func ) {
  42. return {func};
  43. }
  44.  
  45. int main() {
  46. int x = 7;
  47. auto factory = Wrap( [x]( int y, double d ) {
  48. std::cout << "X:" << x << "Y:" << y << "D:" << d << "\n";
  49. } );
  50. void* pvoid;
  51. pvoidary pfunc; // void(*)(void*)
  52. std::tie( pfunc, pvoid ) = factory( 10, 3.14 ); // bind y and d here
  53. pfunc( pvoid ); // calls the wrapped method
  54. }
Success #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
X:7Y:10D:3.14