代码之家  ›  专栏  ›  技术社区  ›  Steve

如何在c++0x中缓存lambda?

  •  7
  • Steve  · 技术社区  · 16 年前

    在C++中使用了大量的Labbda之后,我尝试在C++中使用它们。我目前有一个boost元组(这是真正简化的版本)。

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

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

    3 回复  |  直到 10 年前
        1
  •  7
  •   joshperry    16 年前

    这个 -> 运算符设置lambda的返回类型,如果没有返回类型,则可以忽略它。此外,如果编译器可以推断它,则可以省略返回类型。正如Terry所说,不能将lambda分配给函数指针(GCC不允许这种转换),但可以使用std::function。

    #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);
    }
    
        2
  •  3
  •   Nikola Smiljanić    16 年前

    从…起 Visual C++ Blog

    我提到了将lambdas存储在 tr1::函数。但你不应该这样做 除非有必要,否则 您想要重用lambda,或者只是 想给它起个名字,你可以用

        3
  •  1
  •   Terry Mahaffey    16 年前

    您应该能够在std::函数中存储lambda。在您的示例中,尝试将其存储在

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

    不要忘记汽车(尽管你将无法制作一系列汽车等)。