Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++11

lambda

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

like image 301
Rickard Avatar asked Jul 09 '11 10:07

Rickard


2 Answers

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

like image 184
Armen Tsirunyan Avatar answered Oct 09 '22 08:10

Armen Tsirunyan


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.

like image 34
Puppy Avatar answered Oct 09 '22 10:10

Puppy