C++11 lambda as member variable?

后端 未结 5 1188
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:01

    A bit late, but I have not seen this answer anywhere here. If the lambda has no capture arguments, then it can be implicitly cast to a pointer to a function with the same arguments and return types.

    For example, the following program compiles fine and does what you would expect:

    struct a {
        int (*func)(int, int);
    };
    
    int main()
    {
        a var;
        var.func = [](int a, int b) { return a+b; };
    }
    

    Of course, one of the main advantages of lambdas is the capture clause, and once you add that, then that trick will simply not work. Use std::function or a template, as answered above.

提交回复
热议问题