开发者

Is there any way to use a variable in a lambda which isn't in the current scope?

Basically, I want to know if s开发者_Go百科omething 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;});
}


It kind of sounds like what you are looking for is dynamic scoping. It's definitely not directly supported by C++ or many other languages (the only languages I can think of that do support it directly are Perl and Emacs Lisp); there are good reasons for this which you should meditate on.

I've seen one implementation of dynamic scoping in C++, here:

http://uint32t.blogspot.com/2008/03/lame-implementation-of-dynamic-scoping.html

which you may be able to adapt to your use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜