3 ms·
What do you mean? You can do this just fine: #include <cstdio> #include <functional> using std::printf; using std::function; function<int
by Figs 15y ago
What do you mean? You can do this just fine:
#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;
}
Or did you mean something else?
Edit: Or, you could do something Y-combinator-ish like this: http://rosettacode.org/wiki/Y_combinator#C.2B.2B http://rosettacode.org/wiki/Y_combinator#C.2B.2B but yeah, it is a bit of a hassle compared to named nested functions.