public
Created

returning functions in c++

  • Download Gist
.gitignore
1
/a.out
test_return_function.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
// 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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.