C++ Lambda简明教程

  • C++ Primer Plus 中文 第六版
  • Essential C++ 中文版
  • 深度探索 C++ 对象模型
  • C++ 程序设计语言(1-3)(4) 第四版 英文版
  • A Tour of C++ (Second Edition)
  • Professional C++ (4th Edition)

Lambda

Expressions 表达式

[capture](parameters) -> returnType{
 statements;
}

Capture 关键字

When a lambda definition is executed, for each variable that the lambda captures, a clone of that variable is made (with an identical name) inside the lambda. These cloned variables are initialized from the outer scope variables of the same name at this point.

The captured variables of a lambda are clones of the outer scope variables, not the actual variables

Capture by reference
Capture by value
Capture by both (mixed capture)
int health{ 33 };
int armor{ 100 };
std::vector<CEnemy> enemies{};

[](){}; //default 

//capture health by value 
[health](){}

//can update health value with mutable
[health]() mutable{}

// Capture health and armor by value, and enemies by reference.
[health, armor, &enemies](){};
 
// Capture enemies by reference and everything else by value.
[=, &enemies](){};
 
// Capture armor by value and everything else by reference.
[&, armor](){};
 
// Illegal, we already said we want to capture everything by reference.
[&, &armor](){};
 
// Illegal, we already said we want to capture everything by value.
[=, armor](){};
 
// Illegal, armor appears twice.
[armor, &health, &armor](){};
 
// Illegal, the default capture has to be the first element in the capture group.
[armor, &](){};

Examples 例子

std::string label = "nut";
std::array<std::string, 4> arr{"apple", "banana", "walnut", "lemon"};

// std::find_if takes a pointer to a function
const auto found{std::find_if(arr.begin(), arr.end(), [&label](std::string str) {
     label = "apple";
     return (str.find(label) != std::string::npos);
 })};
auto print = [](auto value) {
        static int count{0};
        std::cout << "count: " << count++ << "value: " << value << std::endl;
    };

print("a");
print("b");
print(1);
print(2);

//we define a lambda and then call it with two different parameters 
//(a string literal parameter, and an integer parameter). This generates 
//two different versions of the lambda (one with a string literal parameter, 
//and one with an integer parameter).

//Most of the time, this is inconsequential. However, note that if the generic 
//lambda uses static duration variables, those variables are not shared between the 
//generated lambdas. 

links:
https://www.learncpp.com/cpp-tutorial/introduction-to-lambdas-anonymous-functions/ https://www.learncpp.com/cpp-tutorial/lambda-captures/

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容