Passing capturing lambda as function pointer

前端 未结 9 2454
-上瘾入骨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:38

    Shafik Yaghmour's answer correctly explains why the lambda cannot be passed as a function pointer if it has a capture. I'd like to show two simple fixes for the problem.

    1. Use std::function instead of raw function pointers.

      This is a very clean solution. Note however that it includes some additional overhead for the type erasure (probably a virtual function call).

      #include 
      #include 
      
      struct Decide
      {
        using DecisionFn = std::function;
        Decide(DecisionFn dec) : dec_ {std::move(dec)} {}
        DecisionFn dec_;
      };
      
      int
      main()
      {
        int x = 5;
        Decide greaterThanThree { [x](){ return x > 3; } };
      }
      
    2. Use a lambda expression that doesn't capture anything.

      Since your predicate is really just a boolean constant, the following would quickly work around the current issue. See this answer for a good explanation why and how this is working.

      // Your 'Decide' class as in your post.
      
      int
      main()
      {
        int x = 5;
        Decide greaterThanThree {
          (x > 3) ? [](){ return true; } : [](){ return false; }
        };
      }
      

提交回复
热议问题