匿名函数是指不需要声明和定义的函数,匿名函数仅需要在使用时候进行创建。匿名函数的 结构如下:
[capture](parameters)->return-type{body}
capture
- []:未定义变量,不允许在函数体内使用任意外部临时变量,全局变量可以使用;
- [x, &y]:x 按值捕获,y 按引用捕获;
- [&]:外部临时变量都按引用捕获;
- [=]:外部临时变量都按值捕获;
- [&, x]:x 按值捕获,其它临时变量按引用捕获;
- [=, &x]:x 按引用捕获. 其它临时变量按值捕获。
示例
[]:未定义变量,不允许在函数体内使用任意外部临时变量,全局变量可以使用
int x = 0;
int main() {
int y = 0;
auto func = [] {
x = 1;
// y = 1; 错误
};
func();
std::cout << x << ' ' << y << std::endl;
return 0;
}
// 输出:1 0
[x, &y]:x 按值捕获,y 按引用捕获
int x = 1, y = 1;
auto func = [x, &y] {
// x = 1; 错误
y = x + 2;
};
func();
std::cout << x << ' ' << y << std::endl;
// 输出:1 3
[&]:外部临时变量都按引用捕获
int x = 1, y = 1;
auto func = [&] {
x = 2;
y = 2;
};
func();
std::cout << x << ' ' << y << std::endl;
// 输出:2 2
[=]:外部临时变量都按值捕获
int x = 1, y = 1;
auto func = [=] {
// x = 2; 错误
return x + y;
};
std::cout << func() << std::endl;
// 输出:2
[&, x]:x 按值捕获,其它临时变量按引用捕获
int x = 1, y = 1;
auto func = [&, x] {
// x = 2; 不允许
y = 2;
};
func();
std::cout << x << ' ' << y << std::endl;
// 输出:1 2
[=, &x]:x 按引用捕获. 其它临时变量按值捕获
int x = 1, y = 1;
auto func = [=, &x] {
x = 2;
// y = 2; 不允许
};
func();
std::cout << x << ' ' << y << std::endl;
// 输出:2 1
参数及返回值
int main() {
auto max = [](int a, int b) -> int {
return a > b ? a : b;
};
std::cout << max(1, 2) << std::endl;
return 0;
}
匿名函数传递
#include <iostream>
void handle(const std::function<void(int, std::string)> &callback) {
callback(200, "success");
}
int main() {
auto callback = [](int status, const std::string &msg) {
std::cout << "status: " << status << ", " + msg << std::endl;
};
handle(callback);
return 0;
}