C++ Lambdas: capture list vs. parameter list

后端 未结 2 1193
走了就别回头了
走了就别回头了 2021-01-31 02:35

According to the C++11 standard, lambda expressions may use variables in the enclosing scope, by means of the capture list, the parameter list or both.

So, let\'s look

相关标签:
2条回答
  • 2021-01-31 02:54

    The point is that with capture, you can keep a state (just as a hand written class with operator() ) in a function-like object. @dau_sama gives a good answer. Here is another example:

    #include <iostream>
    using namespace std;
    
    int main() {
    
      const auto addSome = [](double some){
        return [some](double val){ return some+val; } ;
      };
    
      const auto addFive = addSome(5);
    
      std::cout << addFive(2) << std::endl;
    }
    
    0 讨论(0)
  • 2021-01-31 03:10

    For example using stl algorithms:

    std::vector<int> items;
    int factor;
    auto foundItem = std::find_if(items.begin(), items.end(), 
    [&factor](int const& a) 
    { 
       return a * factor == 100; 
    });
    

    In this case you're called in the lambda for every item in the container and you return if the value multiplied by a captured factor is 100. The code doesn't make much sense, it's just to show you an example where capture and parameter lists matter.

    0 讨论(0)
提交回复
热议问题