fork(3) download
  1. #include <unistd.h>
  2. #include <thread>
  3. #include <chrono>
  4. #include <mutex>
  5. #include <functional>
  6. #include <iostream>
  7. #include <cmath>
  8.  
  9. template <const size_t _UniqueId, typename _Res, typename... _ArgTypes>
  10. struct fun_ptr_helper
  11. {
  12. public:
  13. typedef std::function<_Res(_ArgTypes...)> function_type;
  14.  
  15. static void bind(function_type&& f)
  16. { instance().fn_.swap(f); }
  17.  
  18. static void bind(const function_type& f)
  19. { instance().fn_=f; }
  20.  
  21. static _Res invoke(_ArgTypes... args)
  22. { return instance().fn_(args...); }
  23.  
  24. typedef decltype(&fun_ptr_helper::invoke) pointer_type;
  25. static pointer_type ptr()
  26. { return &invoke; }
  27.  
  28. private:
  29. static fun_ptr_helper& instance()
  30. {
  31. static fun_ptr_helper inst_;
  32. return inst_;
  33. }
  34.  
  35. fun_ptr_helper() {}
  36.  
  37. function_type fn_;
  38. };
  39.  
  40. template <const size_t _UniqueId, typename _Res, typename... _ArgTypes>
  41. typename fun_ptr_helper<_UniqueId, _Res, _ArgTypes...>::pointer_type
  42. get_fn_ptr(const std::function<_Res(_ArgTypes...)>& f)
  43. {
  44. fun_ptr_helper<_UniqueId, _Res, _ArgTypes...>::bind(f);
  45. return fun_ptr_helper<_UniqueId, _Res, _ArgTypes...>::ptr();
  46. }
  47.  
  48. template<typename T>
  49. std::function<typename std::enable_if<std::is_function<T>::value, T>::type>
  50. make_function(T *t)
  51. {
  52. return {t};
  53. }
  54.  
  55. int main()
  56. {
  57. std::cout << (void*)get_fn_ptr<0>(make_function(::sin))<<std::endl;
  58. return 0;
  59. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
0x8048b50