fork 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 <typename Res, typename... Args>
  10. struct function_ptr_helper
  11. {
  12. public:
  13. template<typename function_type>
  14. static auto bind(function_type&& f) { func = std::forward<function_type>(f); }
  15.  
  16. static auto invoke(Args... args) { return func(args...); }
  17. static auto* ptr() { return &invoke; }
  18.  
  19. private:
  20. static std::function<Res(Args ...)> func;
  21. };
  22.  
  23. template <typename Res, typename... Args>
  24. std::function<Res(Args ...)> function_ptr_helper<Res, Args...>::func;
  25.  
  26. template <typename Res, typename ... Args>
  27. auto* get_fn_ptr(std::function<Res(Args...)> const& f)
  28. {
  29. using type = function_ptr_helper<Res, Args...>;
  30.  
  31. type::bind(f);
  32. return type::ptr();
  33. }
  34.  
  35. struct test
  36. {
  37. double operator()(double, double) const
  38. {
  39. return 1.0 + c;
  40. }
  41. double c=1.0;
  42. };
  43.  
  44.  
  45. int main()
  46. {
  47. std::function<double(double,double)> f = test{};
  48.  
  49. typedef double (*funcPtr)(double,double);
  50.  
  51. funcPtr fp = get_fn_ptr(f);
  52. return 0;
  53. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
Standard output is empty