fork download
  1. #include <cstdlib>
  2. #include <tuple>
  3. #include <functional>
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. // For generic types that are functors, delegate to its 'operator()'
  8. template <typename T>
  9. struct function_traits
  10. : public function_traits<decltype(&T::operator())>
  11. {};
  12.  
  13. // for pointers to member function
  14. template <typename ClassType, typename ReturnType, typename... Args>
  15. struct function_traits<ReturnType(ClassType::*)(Args...) const> {
  16. //enum { arity = sizeof...(Args) };
  17. typedef function<ReturnType (Args...)> f_type;
  18. };
  19.  
  20. // for pointers to member function
  21. template <typename ClassType, typename ReturnType, typename... Args>
  22. struct function_traits<ReturnType(ClassType::*)(Args...) > {
  23. typedef function<ReturnType (Args...)> f_type;
  24. };
  25.  
  26. // for function pointers
  27. template <typename ReturnType, typename... Args>
  28. struct function_traits<ReturnType (*)(Args...)> {
  29. typedef function<ReturnType (Args...)> f_type;
  30. };
  31.  
  32. template <typename L>
  33. typename function_traits<L>::f_type make_function(L l){
  34. return (typename function_traits<L>::f_type)(l);
  35. }
  36.  
  37. long times10(int i) { return long(i*10); }
  38.  
  39. struct X {
  40. double operator () (float f, double d) { return d*f; }
  41. };
  42.  
  43. // test code
  44. int main()
  45. {
  46. auto lambda = [](int i) { return long(i*10); };
  47. typedef function_traits<decltype(lambda)> traits;
  48. traits::f_type ff = lambda;
  49.  
  50. cout << make_function([](int i) { return long(i*10); })(2) << ", " << make_function(times10)(2) << ", " << ff(2) << endl;
  51. cout << make_function(X{})(2,3.0) << endl;
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
20, 20, 20
6