在 C# 中大量使用 lambda 后,我尝试在 C++ 中使用 lambda。我目前有一个 boost 元组(这是真正简化的版本)。
typedef shared_ptr<Foo> (*StringFooCreator)(std::string, int, bool)
typedef tuple<StringFooCreator> FooTuple
然后,我将全局命名空间中的一个函数加载到我的 FooTuple 中。理想情况下,我想用 lambda 替换它。
tuplearray[i] = FooTuple([](string bar, int rc, bool eom) -> {return shared_ptr<Foo>(new Foo(bar, rc, eom));});
我无法弄清楚 lambda 元组的函数签名应该是什么。它显然不是一个函数指针,但我无法弄清楚 lambda 的签名应该是什么。现在 lambda 的资源都非常匮乏。我意识到 C++0x 目前正在不断变化,但我很好奇如何让它发挥作用。我也意识到有更简单的方法可以做到这一点,但我只是在玩 C++0x。我使用的是 Intel 11.1 编译器。
I'm trying to work with lambda's in C++ after having used them a great deal in C#. I currently have a boost tuple (this is the really simplified version).
typedef shared_ptr<Foo> (*StringFooCreator)(std::string, int, bool)
typedef tuple<StringFooCreator> FooTuple
I then load a function in the global namespace into 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 should be for the lambda tuple. Its obviously not a function pointer, but I can't figure out what a lambda's signature should be. The resources for lambda's are all pretty thin right now. I realize C++0x is in flux at the moment, but I was curious about how to get this to work. I also realize there are simpler ways to do this, but I'm just playing around with C++0x. I am using the Intel 11.1 compiler.
发布评论
评论(3)
->
运算符设置 lambda 的返回类型,如果没有返回类型,则可以省略。另外,如果编译器可以推断出它,则可以省略返回类型。就像 Terry 所说,你不能将 lambda 分配给函数指针(GCC 不正确地允许这种转换),但你可以使用 std::function。此代码适用于 GCC 和 VC10(从 VC 的包含中删除 tr1/):
The
->
operator sets the return type of the lambda, in the case of no return type it can be omitted. Also, if it can be inferred by the compiler you can omit the return type. Like Terry said, you can't assign a lambda to a function pointer (GCC improperly allows this conversion) but you can use std::function.This code works on GCC and VC10 (remove tr1/ from the includes for VC):
来自 Visual C++ 博客
From Visual C++ Blog
您应该能够将 lambda 存储在 std::function 中。在您的示例中,尝试将其存储在
std::function(std::string,int,bool)>
不要忘记 auto (尽管您不会无法制作一系列汽车等)。
You should be able to store a lambda in a std::function. In your example, try storing it in a
std::function<std::shared_ptr<Foo>(std::string,int,bool)>
Don't forget about auto (although you won't be able to make an array of auto's, etc).