fork(12) download
  1. #include <boost/optional.hpp>
  2. #include <boost/bind.hpp>
  3. #include <iostream>
  4. #include <ostream>
  5. using namespace std;
  6.  
  7. template<unsigned ID,typename Functor>
  8. boost::optional<Functor> &get_local()
  9. {
  10. static boost::optional<Functor> local;
  11. return local;
  12. }
  13.  
  14. template<unsigned ID,typename Functor>
  15. typename Functor::result_type wrapper()
  16. {
  17. return get_local<ID,Functor>().get()();
  18. }
  19.  
  20. template<typename ReturnType>
  21. struct Func
  22. {
  23. typedef ReturnType (*type)();
  24. };
  25.  
  26. template<unsigned ID,typename Functor>
  27. typename Func<typename Functor::result_type>::type get_wrapper(Functor f)
  28. {
  29. (get_local<ID,Functor>()) = f;
  30. return wrapper<ID,Functor>;
  31. }
  32.  
  33. // ----------------------------------------------------------------------
  34.  
  35. void test(void (*fptr)())
  36. {
  37. fptr();
  38. }
  39.  
  40. struct SomeStruct
  41. {
  42. int data;
  43. void some_method()
  44. {
  45. cout << data << endl;
  46. }
  47. void another_method()
  48. {
  49. cout << -data << endl;
  50. }
  51. };
  52.  
  53. int main()
  54. {
  55. SomeStruct local[] = { {11}, {22}, {33} };
  56.  
  57. test(get_wrapper<0>( boost::bind(&SomeStruct::some_method,local[0]) ));
  58. test(get_wrapper<1>( boost::bind(&SomeStruct::another_method,local[0]) ));
  59.  
  60. test(get_wrapper<2>( boost::bind(&SomeStruct::some_method,local[1]) ));
  61. test(get_wrapper<3>( boost::bind(&SomeStruct::another_method,local[1]) ));
  62.  
  63. test(get_wrapper<4>( boost::bind(&SomeStruct::some_method,local[2]) ));
  64. test(get_wrapper<5>( boost::bind(&SomeStruct::another_method,local[2]) ));
  65. }
  66.  
Success #stdin #stdout 0.01s 2728KB
stdin
Standard input is empty
stdout
11
-11
22
-22
33
-33