fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. template <typename T>
  5. class yoba {
  6. public:
  7. yoba(const T& n, std::function<T(T)> func)
  8. : n(n), func(func) {}
  9.  
  10. T next() {
  11. n = func(n);
  12. return n;
  13. }
  14. private:
  15. T n;
  16. std::function<T(T)> func;
  17. };
  18.  
  19.  
  20. template <typename T>
  21. struct return_type : public return_type<decltype(&T::operator())> {};
  22.  
  23. template <typename C, typename R, typename... Args>
  24. struct return_type<R(C::*)(Args...) const> {
  25. using type = R;
  26. };
  27.  
  28. template <typename Func>
  29. auto make_yoba(Func func) -> std::function<yoba<typename return_type<Func>::type>(typename return_type<Func>::type)> {
  30. using T = typename return_type<Func>::type;
  31. return [func] (const T& n) {
  32. return yoba<T>(n, func);
  33. };
  34. }
  35.  
  36. auto main() -> int {
  37. auto yoba_int = make_yoba([] (int n) -> int {
  38. return n + 1;
  39. });
  40. auto yoba_double = make_yoba([] (double n) -> double {
  41. return n / 2;
  42. });
  43.  
  44. auto yoba_int5 = yoba_int(5);
  45.  
  46. std::cout << yoba_int5.next() << std::endl;
  47. std::cout << yoba_int5.next() << std::endl;
  48.  
  49. auto yoba_double238 = yoba_double(2.38);
  50.  
  51. std::cout << yoba_double238.next() << std::endl;
  52. std::cout << yoba_double238.next() << std::endl;
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
6
7
1.19
0.595