简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
1.前言
本篇目的:理解C++11的lambda(即匿名函数)的回调函数作为参数传递的用法。
2.用法
#include <iostream>
using namespace std;
// 定义一个回调函数模板
template <typename Callback>
int test_lambda_callback(Callback callback) {
// 调用传入的lambda表达式
return callback(1,2);
}
template <typename Callback>
void test_lambda_callback_01(Callback callback) {
// 调用传入的lambda表达式
callback(1,2,3);
}
int bb = 30;
auto FuncAdd = [](int a, int b)->int {
printf("xxx---------->%s(), line = %d, a = %d, b = %d, xx = %d\n",__FUNCTION__,__LINE__,a,b,bb);
return a + b;
};
int main() {
//1.使用lambda表达式作为回调函数
int sum = FuncAdd(2, 3);
//2.外部变量值传递:[sum]
test_lambda_callback([sum](int a, int b) {
printf("xxx---------->%s(), line = %d, a = %d, b = %d, sum = %d\n",__FUNCTION__,__LINE__,a,b,sum);
return a + b;
});
//3.外部变量引用传递:[&sum]
test_lambda_callback([&sum](int a, int b) {
printf("xxx---------->%s(), line = %d, a = %d, b = %d, sum = %d\n",__FUNCTION__,__LINE__,a,b,sum);
return a + b;
});
//4.无返回值的情况:外部变量引用传递:[&sum]
test_lambda_callback_01([&sum](int a, int b, int c) {
printf("xxx---------->%s(), line = %d, a = %d, b = %d, c = %d, sum = %d\n",__FUNCTION__,__LINE__,a,b,c,sum);
});
return 0;
}
打印:
xxx---------->operator()(), line = 20, a = 2, b = 3, xx = 30
xxx---------->operator()(), line = 31, a = 1, b = 2, sum = 5
xxx---------->operator()(), line = 37, a = 1, b = 2, sum = 5
xxx---------->operator()(), line = 43, a = 1, b = 2, c = 3, sum = 5