Skip to content

Instantly share code, notes, and snippets.

@zed
Created November 5, 2011 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/1342212 to your computer and use it in GitHub Desktop.
Save zed/1342212 to your computer and use it in GitHub Desktop.
returning functions in c++
// http://stackoverflow.com/questions/4726768/returning-functions-in-c
// g++ -std=c++0x test_return_function.cpp && ./a.out
#include <functional>
#include <iostream>
namespace {
std::function<int()>
make_counter(int start=0){ // closure
return [start]() mutable { return start++; };
}
typedef int (*identity_t)(int);
identity_t
identity() { // stateless lambda
return [](int x) { return x; };
}
}
int main() {
using namespace std;
auto count = make_counter(4);
auto count2 = make_counter();
cout << count() << " ";
cout << count2() << " ";
cout << count() << " ";
cout << count() << " ";
cout << count2() << endl;
auto same = identity();
cout << same(4) << " "
<< same(0) << " "
<< same(5) << " "
<< same(6) << " "
<< same(1) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment