Created
August 5, 2013 06:33
-
-
Save azmfaridee/6153885 to your computer and use it in GitHub Desktop.
A simple example of closures in C++11. Also shows how you can keep a vector of 'functors'. You'd need a C++11 compatible compiler, I wrote and compiled this in XCode 4.6.3 :)
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 <iostream> | |
#include <vector> | |
using namespace std; | |
int main(int argc, const char * argv[]) { | |
vector<function<void()>> functions; | |
for (int i = 0; i < 5; i++) { | |
functions.push_back([i] () { | |
cout << "I have value of " << i << endl; | |
}); | |
} | |
for_each(functions.begin(), functions.end(), [] (function<void()> f) { | |
f(); | |
}); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is also possible in Objective C, using 'blocks'. The example assumes ARC, no memory cleanup. Note that when adding the 'block' to the
NSMutableArray
you need to use thecopy
message (regardless of using ARC).