fork download
  1. #include <iostream>
  2. #include <tuple>
  3.  
  4. //function traits
  5. template <typename T>
  6. struct function_traits : public function_traits<decltype(&T::operator())>
  7. {};
  8.  
  9. template <typename C, typename R, typename... A>
  10. struct function_traits<R(C::*)(A...) const>
  11. {
  12. template <size_t i>
  13. struct arg
  14. {
  15. typedef typename std::tuple_element<i, std::tuple<A...>>::type type;
  16. };
  17. };
  18.  
  19. template<typename InArg, typename Function>
  20. class selfCompose {
  21. Function f;
  22. public:
  23. selfCompose(Function f): f(f) {}
  24. auto operator() (InArg x) -> decltype(f(f(x)))
  25. {
  26. return f(f(x));
  27. }
  28. };
  29.  
  30. template<typename Fun>
  31. selfCompose<typename function_traits<Fun>::template arg<0>::type, Fun>
  32. make_selfCompose(Fun f)
  33. {
  34. typedef typename function_traits<Fun>::template arg<0>::type InArg;
  35. return selfCompose<InArg, decltype(f)>(f);
  36. }
  37.  
  38. int main() {
  39. auto f = [](int x){return x*x;};
  40. std::cout << make_selfCompose(f)(4)
  41. << std::endl;
  42. return 0;
  43. }
  44.  
  45.  
Success #stdin #stdout 0s 2884KB
stdin
Standard input is empty
stdout
256