Created
September 8, 2014 16:10
-
-
Save ramntry/193a95acfda72e847415 to your computer and use it in GitHub Desktop.
C++11 Lambdas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <cassert> | |
| #include <functional> | |
| std::function<int()> create_counter(int const delta) { | |
| int counter = 0; | |
| return [delta, counter]() mutable { | |
| return counter += delta; | |
| }; | |
| } | |
| int main() { | |
| auto by1counter = create_counter(1); | |
| auto by10counter = create_counter(10); | |
| assert(by1counter() == 1); | |
| assert(by1counter() == 2); | |
| assert(by10counter() == 10); | |
| assert(by10counter() == 20); | |
| assert(by1counter() == 3); | |
| assert(by10counter() == 30); | |
| assert(by1counter() == 4); | |
| assert(by10counter() == 40); | |
| auto by100counter = create_counter(100); | |
| assert(by100counter() == 100); | |
| assert(by1counter() == 5); | |
| assert(by100counter() == 200); | |
| assert(by10counter() == 50); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment