How to cache lambda in C ++ 0x?

I am trying to work with lambda in C ++ after using them in C #. I currently have a boot tuple (this is a really simplified version).

typedef shared_ptr<Foo> (*StringFooCreator)(std::string, int, bool) typedef tuple<StringFooCreator> FooTuple 

Then I load the function into the global namespace in my FooTuple. Ideally, I would like to replace this with a lambda.

 tuplearray[i] = FooTuple([](string bar, int rc, bool eom) -> {return shared_ptr<Foo>(new Foo(bar, rc, eom));}); 

I can't figure out what the function signature for the lambda tuple should be. Obviously, this is not a pointer to a function, but I cannot understand what a lambda signature is. Resources for lambda are pretty thin right now. I understand that C ++ 0x is now on the move, but I was curious how to make this work. I also understand that there are simpler ways to do this, but I'm just playing with C ++ 0x. I am using the Intel 11.1 compiler.

+7
c ++ boost lambda c ++ 11 tuples
source share
3 answers

The operator -> sets the return type of lambda; in the absence of a return type, it can be omitted. Also, if it can be output by the compiler, you can omit the return type. As Terry said, you cannot assign a lambda to a function pointer (GCC does not allow this conversion correctly), but you can use std :: function.

This code works on GCC and VC10 (remove tr1 / from inclusions for VC):

 #include <tr1/tuple> #include <tr1/functional> #include <tr1/memory> using namespace std; using namespace std::tr1; class Foo{}; typedef function<shared_ptr<Foo>(string, int, bool)> StringFooCreator; typedef tuple<StringFooCreator> FooTuple; int main() { FooTuple f( [](string bar, int rc, bool eom) { return make_shared<Foo>(); } ); shared_ptr<Foo> pf = get<0>(f)("blah", 3, true); } 
+7
source share

From Visual C ++ Blog

I mentioned storing lambda in the TR1 :: function. But you should not do that if necessary, since the tr1 :: function has some overhead. If you want to reuse lambda or just want to give it a name, you can use auto.

+3
source share

You should be able to store lambda in the std :: function. In your example, try saving it to

std::function<std::shared_ptr<Foo>(std::string,int,bool)>

Do not forget about the car (although you can not create an array of cars, etc.).

+1
source share

All Articles