Is there a way to use a variable in a lambda that is not in the current scope?

advertisements

Basically, I want to know if something like the below is possible? If this isn't possible is there any way to fake it?

#include <iostream>
using namespace std;

template<typename Functor>
void foo(Functor func)
{
    auto test = [](Functor f){ int i = 5; f(); };
    test(func);
}

int main()
{
    foo([](){ cout << i << endl;});
}


You could make i an argument to the function.

#include <iostream>
using namespace std;

template<typename Functor>
void foo(Functor func)
{
    auto test = [](Functor f){ f(5); };
    test(func);
}

int main()
{
    foo([](int i){ cout << i << endl;});
}

Otherwise, I think you have to declare i in a scope that is accessible from both places, e.g. as a global variable:

#include <iostream>
using namespace std;

static int i;    // <--- :(

template<typename Functor>
void foo(Functor func)
{
    auto test = [](Functor f){ i = 5; f(); };
    test(func);
}

int main()
{
    foo([](){ cout << i << endl;});
}