C++11 lambda as member variable?

后端 未结 5 1237
Happy的楠姐
Happy的楠姐 2021-01-31 07:24

Can lambda\'s be defined as class members?

For example, would it be possible to rewrite the code sample below using a lambda instead of a function object?



        
5条回答
  •  半阙折子戏
    2021-01-31 08:12

    Templates make it possible without type erasure, but that's it:

    template
    struct foo {
        T t;
    };
    
    template
    foo::type>
    make_foo(T&& t)
    {
        return { std::forward(t) };
    }
    
    // ...
    auto f = make_foo([] { return 42; });
    

    Repeating the arguments that everyone has already exposed: []{} is not a type, so you can't use it as e.g. a template parameter like you're trying. Using decltype is also iffy because every instance of a lambda expression is a notation for a separate closure object with a unique type. (e.g. the type of f above is not foo.)

提交回复
热议问题