Rickard
Rickard

Reputation: 677

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

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

Upvotes: 5

Views: 2691

Answers (2)

Puppy
Puppy

Reputation: 146968

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.

Upvotes: 5

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133072

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

Upvotes: 7

Related Questions