Guest User

Untitled

a guest
Jan 17th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. // C++11
  2. #include <functional>
  3. using fp = std::function<int()>;
  4.  
  5. fp f1(int i)
  6. {
  7. i *= 100;
  8. return [i]() mutable { return i++; };
  9. }
  10.  
  11. fp f2(int a, int b)
  12. {
  13. return [a, b]() mutable { a++; b--; return a * b; };
  14. }
  15.  
  16. int main()
  17. {
  18. fp p;
  19. int i;
  20.  
  21. p = f1(1);
  22. i = p();
  23. i = p();
  24. i = p();
  25.  
  26. p = f2(3, 5);
  27. i = p();
  28. i = p();
  29. i = p();
  30.  
  31. return 0;
  32. }
  33.  
  34. class __closure {
  35. public:
  36. __closure(const __closure&) = default;
  37. ~__closure() = default;
  38.  
  39. int operator()();
  40.  
  41. private:
  42. __closure(unspecified arguments);
  43. __closure& operator=(const __closure&) = default;
  44. __closure() = delete;
  45.  
  46. int i;
  47. };
  48.  
  49. class __closure {
  50. using signature = int();
  51. static int body();
  52. public:
  53. int operator() { return body(); }
  54. operator signature*() { return &body; }
  55. ...
  56.  
  57. fp f(int i)
  58. {
  59. i *= 100
  60. return [i]() mutable { return i++; };
  61. }
  62.  
  63. #include <iostream>
  64. #include <functional>
  65.  
  66. using fp = std::function<int()>;
  67.  
  68. fp f(int i)
  69. {
  70. i *= 100;
  71.  
  72. struct A
  73. {
  74. A(int i) : i(i) {}
  75. int i;
  76.  
  77. int operator ()() { return i++; }
  78. };
  79.  
  80. return A( i );
  81. }
  82.  
  83. int main()
  84. {
  85. fp p;
  86. int i;
  87.  
  88. p = f(1);
  89. std::cout << ( i = p() ) << std::endl;
  90. std::cout << ( i = p() ) << std::endl;
  91. std::cout << ( i = p() ) << std::endl;
  92. }
  93.  
  94. 100
  95. 101
  96. 102
  97.  
  98. class Lambda
  99. {
  100. захваченные переменные
  101.  
  102. type operator()(params) { ... };
  103.  
  104. Lambda L;
  105.  
  106. L();
Add Comment
Please, Sign In to add comment