In C++ you cannot declare a function inside of another function. Luckily though we can work around that by creating a closure object using a lambda expression. Your code, adapted to that would become
template <typename Integer>
auto start(Integer n)
{
return [n]() mutable { return ++n; };
}
And then you would use it like
std::cout << start(1)();
There are couple things to note about the above example. First, the capture of n
. Since the closure object is be returned out of the scope of start
, we have to capture it by value, otherwise the closure will have a dangling reference. Secondly, the use of mutable
in the lambda expression. That is there because by default the operator()
is const
. That means you could not modify n
. Using mutable
removes the const
and allows n
to be modified.