std::function类的使用示例
std::function
是C++标准库中的一个模板类,用于封装可调用的目标,比如函数、函数指针、成员函数指针、Lambda表达式等,使得它们可以像普通函数一样被调用。这种灵活性使得std::function
在许多场景下都非常有用。
以下是std::function
的一般用法:
1. 封装函数指针
1.1 不带参数和返回值
#include <functional>
#include <iostream>
void sayHello() {
std::cout << "Hello!" << std::endl;
}
int main() {
std::function<void()> func = sayHello;
func(); // 调用 sayHello
return 0;
}
1.2 带参数和返回值
#include <functional>
#include <iostream>
// 普通函数
int multiply(int a, int b) {
return a * b;
}
int main() {
// 封装带参数和返回值的普通函数
std::function<int(int, int)> multiply_function = multiply;
// 调用封装的普通函数
int result = multiply_function(5, 4);
std::cout << "Result: " << result << std::endl; // 输出 20
return 0;
}
2. 封装Lambda表达式
2.1 不带参数和返回值
#include <functional>
#include <iostream>
int main() {
std::function<int(int, int)> add = [](int a, int b) { return a + b; };
std::cout << add(3, 4) << std::endl; // 输出 7
return 0;
}
2.2 带参数和返回值
#include <functional>
#include <iostream>
int main() {
// 封装带参数和返回值的匿名函数
std::function<int(int, int)> add = [](int a, int b) {
return a + b;
};
// 调用封装的匿名函数
std::cout << "Sum: " << add(3, 4) << std::endl; // 输出 7
return 0;
}
3. 作为容器元素
3.1 不带参数和返回值
#include <functional>
#include <iostream>
#include <vector>
int main() {
std::vector<std::function<void()>> funcs;
funcs.push_back([]() { std::cout << "Function 1" << std::endl; });
funcs.push_back([]() { std::cout << "Function 2" << std::endl; });
for (const auto& func : funcs) {
func();
}
return 0;
}
3.2 不带参数和返回值
大概可以自行推断了。
本文作者:FreeCheng
本文链接:https://www.cnblogs.com/freecheng/p/17985046
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步