#include <cstdio>
#include <functional>
using std::printf;
using std::function;
function<int ()> f(int x)
{
function<int ()> g = [x]()
{
return 2 * x;
};
return g;
}
int main()
{
auto f1 = f(5);
auto f2 = f(6);
printf("f1() = %d, f2() = %d\n", f1(), f2());
return 0;
}
(Which prints `f1() = 10, f2() = 12`)
Or did you mean nested functions in the sense of being able to form named closures so that they can call themselves with a headache? It is admittedly more or a pain to do that (if you want to return a closure), but it is still doable, using new and delete:
#include <cstdio>
#include <functional>
using std::printf;
using std::function;
function<int (int)>* f(int x)
{
function<int (int)>* g = new function<int (int)>();
*g = [g, x](int n)
{
if(n <= 0)
return 1;
else
return x + n * (*g)(n-1);
};
return g;
}
int main()
{
auto f1 = f(0);
auto f2 = f(1);
printf("f1() = %d, f2() = %d\n", (*f1)(5), (*f2)(5));
delete f1;
delete f2;
return 0;
}