Skip to content

Instantly share code, notes, and snippets.

@ramntry
Created September 8, 2014 16:10
Show Gist options
  • Select an option

  • Save ramntry/193a95acfda72e847415 to your computer and use it in GitHub Desktop.

Select an option

Save ramntry/193a95acfda72e847415 to your computer and use it in GitHub Desktop.
C++11 Lambdas
#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