Skip to content

Instantly share code, notes, and snippets.

@azmfaridee
Created August 5, 2013 06:33
Show Gist options
  • Save azmfaridee/6153885 to your computer and use it in GitHub Desktop.
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 :)
#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;
}
@azmfaridee
Copy link
Author

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 the copy message (regardless of using ARC).

#import <Cocoa/Cocoa.h>

int main(int argc, char *argv[])
{
    NSMutableArray *array = [NSMutableArray array];
    for (int  i = 0; i < 5; i++) {
        [array addObject:[^() {
            NSLog(@"I have Value of %d", i);
        } copy]];
    }

    for (id (^fn)() in array) {
        fn();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment