开发者

Store C++0x lambda-functions in a std::map/vector for later use in Visual Studio

开发者 https://www.devze.com 2023-03-19 05:32 出处:网络
Im working on a small graphics engine project that and I want to it to be crossed platform (someday). I been developing with latest version of MinGW and C++0x.

Im working on a small graphics engine project that and I want to it to be crossed platform (someday). I been developing with latest version of MinGW and C++0x. For event listeners I use lambda functions stored in a std::map that will be called when a certain event 开发者_运维百科occurs. It works really smooth with MinGW but the other day when I tried it in Visual Studio (latest version) it failed.

I inspected the type of the lambdas and even if I define two lambdas to be excatly the same, they get different types (annonymous namespace:: and annonymous namespace::)).

For example i have this std::map to store scroll listeners

std::map<int,void (*)(int p)> scrollListenerFunctions;

And then I can add a listener by just do:

addScrollListener([](int p){/* Do something here */});

As I said, this works fine in MinGW but fails in Visual Studio, is there a way of doing it so it works in both and is it even possible to store lambdas in VS atm?

If you wnat/need to see more code you can find it here http://code.google.com/p/aotk/source/browse/ the lambda maps are located in window.h / window.cpp


instead of this:

std::map<int,void (*)(int p)> scrollListenerFunctions;

you must have this:

std::map<int,std::function<void(int p)> > scrollListenerFunctions;

The thing is that a lambda is not convertible to a function-pointer. You need a more generic callback wrapper, like std::function


Stateless lambdas can convert to function pointers but Visual Studio does not yet support it, it was added after they implemented lambdas. You really should be using std::function anyway.

0

精彩评论

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