Passing capturing lambda as function pointer

前端 未结 9 2214
-上瘾入骨i
-上瘾入骨i 2020-11-21 06:58

Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.

Consider the follo

9条回答
  •  礼貌的吻别
    2020-11-21 07:26

    Not a direct answer, but a slight variation to use the "functor" template pattern to hide away the specifics of the lambda type and keeps the code nice and simple.

    I was not sure how you wanted to use the decide class so I had to extend the class with a function that uses it. See full example here: https://godbolt.org/z/jtByqE

    The basic form of your class might look like this:

    template 
    class Decide
    {
    public:
        Decide(Functor dec) : _dec{dec} {}
    private:
        Functor _dec;
    };
    

    Where you pass the type of the function in as part of the class type used like:

    auto decide_fc = [](int x){ return x > 3; };
    Decide greaterThanThree{decide_fc};
    

    Again, I was not sure why you are capturing x it made more sense (to me) to have a parameter that you pass in to the lambda) so you can use like:

    int result = _dec(5); // or whatever value
    

    See the link for a complete example

提交回复
热议问题