Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // C++11
- #include <functional>
- using fp = std::function<int()>;
- fp f1(int i)
- {
- i *= 100;
- return [i]() mutable { return i++; };
- }
- fp f2(int a, int b)
- {
- return [a, b]() mutable { a++; b--; return a * b; };
- }
- int main()
- {
- fp p;
- int i;
- p = f1(1);
- i = p();
- i = p();
- i = p();
- p = f2(3, 5);
- i = p();
- i = p();
- i = p();
- return 0;
- }
- class __closure {
- public:
- __closure(const __closure&) = default;
- ~__closure() = default;
- int operator()();
- private:
- __closure(unspecified arguments);
- __closure& operator=(const __closure&) = default;
- __closure() = delete;
- int i;
- };
- class __closure {
- using signature = int();
- static int body();
- public:
- int operator() { return body(); }
- operator signature*() { return &body; }
- ...
- fp f(int i)
- {
- i *= 100
- return [i]() mutable { return i++; };
- }
- #include <iostream>
- #include <functional>
- using fp = std::function<int()>;
- fp f(int i)
- {
- i *= 100;
- struct A
- {
- A(int i) : i(i) {}
- int i;
- int operator ()() { return i++; }
- };
- return A( i );
- }
- int main()
- {
- fp p;
- int i;
- p = f(1);
- std::cout << ( i = p() ) << std::endl;
- std::cout << ( i = p() ) << std::endl;
- std::cout << ( i = p() ) << std::endl;
- }
- 100
- 101
- 102
- class Lambda
- {
- захваченные переменные
- type operator()(params) { ... };
- Lambda L;
- L();
Add Comment
Please, Sign In to add comment