Lambda 表达式
lambda表达式源于函数式编程的概念,它可以就地匿名定义目标函数或函数对象,不需要额外写一个命名函数或者函数对象。lambda表达式的类型在C++11中被称为“闭包类型”,也可以理解为是一个仿函数(带operator()类)
以下只是简单的用法 要想理解建议看看我接下来写的 bind和function两篇文章
无参
#include<iostream> using namespace std; int main() { auto f = []() {cout << "hello world" << endl; };//[]这个是捕获列表 除了lambda以外的参数()是函数参数列表 return 0; }
无捕获列表有参
#include<iostream> using namespace std; int main() { [](int x) {cout << x << endl; }(5);//打印的是5 return 0; }
有捕获列表 具体值传递
有捕获列表 具体值传递 #include<iostream> using namespace std; int main() { int a = 10; cout << "a的地址" << &a << endl; [a]() {cout << "a的地址" << &a << endl; }();//打印的结果就是两个地址不一样是复制 return 0; }
#include <iostream> #include <functional> int main() { // 使用 std::function 包装 Lambda 表达式 std::function<int(int, int)> func = [](int a, int b) { return a * b; }; // 调用包装的 Lambda 表达式 int result = func(3, 4); std::cout << "Result: " << result << std::endl; // 输出:Result: 12 return 0; }
函数对象
#include <iostream> #include <functional> // 函数对象 struct Multiply { int operator()(int a, int b) const { return a * b; } }; int main() { // 使用 std::function 包装函数对象 std::function<int(int, int)> func = Multiply(); // 调用包装的函数对象 int result = func(3, 4); std::cout << "Result: " << result << std::endl; // 输出:Result: 12 return 0; }
多态性
#include <iostream> #include <functional> void printMessage(const std::string& message) { std::cout << message << std::endl; } void printNumber(int number) { std::cout << "Number: " << number << std::endl; } int main() { // 使用 std::function 容纳不同签名的函数 std::function<void(const std::string&)> func1 = printMessage; std::function<void(int)> func2 = printNumber; // 调用包装的函数 func1("Hello, world!"); // 输出:Hello, world! func2(42); // 输出:Number: 42 return 0; }
绑定参数
#include <iostream> #include <functional> int add(int a, int b) { return a + b; } int main() { // 使用 std::bind 绑定参数 std::function<int(int)> add5 = std::bind(add, std::placeholders::_1, 5); // 调用包装的函数 int result = add5(10); std::cout << "Result: " << result << std::endl; // 输出:Result: 15 return 0; }
这些示例涵盖了 std::function
的基本用法,包括包装函数、Lambda 表达式、函数对象、多态性、绑定参数以及清空或重置等方面。希望这能够帮助你更好地理解和使用 std::function
。
Protocol Buffers(protobuf)是一种由Google开发的轻量级的数据交换格式,它可以用于结构化数据的序列化,类似于 XML 或 JSON,但更轻量、更高效。Protocol Buffers 不仅用于数据的序列化和反序列化,还可以定义数据结构和接口。