当前位置:网站首页>Lambda expression

Lambda expression

2022-06-09 08:33:00 A struggling Xiaobai 1

1. Introduce

Lambda The expression is an anonymous function , That is, functions without names

yes c++11 Newly added features , Pay attention to whether the compiler supports C++11, The aim is to simplify programming , The underlying implementation can be understood as a functor

2. grammar

[capture list] (parameter list) mutable -> return type { function body }

capture list: Capture list , It must not be omitted

params list: parameter list , Can be passed by value or by reference , It can be omitted

mutable: optional , It can be omitted

ret: Return value , If the compiler can automatically derive the return value type , You can also omit

function body: The body of the function , It must not be omitted

To sum up, the simplest Lambda An expression is shaped like [] {} The appearance of

3. Capture list         

[] Don't capture any variables

[&] Capture all variables in the external scope , And use it as a reference in the function body ( Capture by reference )

[=] Capture all variables in the external scope , And use it as a copy in the function weight ( Capture by value )

[=,&foo] Capture all variables in the external scope by value , And capture by reference foo Variable

[&,=foo] Capture all variables in the external scope by reference , And capture by value foo Variable

[bar] Capture by value bar Variable , At the same time, other variables are not captured

[this] Capture... In the current class this The pointer , Let the expression have the same access rights as the current class member function .

notes 1: The capture list is passed by value to capture the constancy , To add mutable The copied copy can only be modified , Capture by reference is not constant , Parameter lists are also not constant .

notes 2: The capture list can only capture local variables in the current scope , Local variables or nonlocal variables outside the scope will report errors .

notes 3:lambda Cannot assign values between expressions , Even if it looks the same type .

4. Use

Law 1: First define a function object to accept anonymous function objects , Then call the function

auto f1 = []() { cout << "Hello world!"; };
f1();

Law 2: Use directly while defining

[]() {cout << "Hello C++!"; } ();

Some use of capture lists , Follow the instructions to simply type a few codes , You can understand !

原网站

版权声明
本文为[A struggling Xiaobai 1]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090824042861.html