std::functional
时间: 2024-03-29 22:31:21 浏览: 47
std::function是C++中的一个通用函数封装器,可以用来包装任何可调用对象,例如函数、成员函数、lambda表达式等,并且可以像函数一样调用包装后的可调用对象。
以下是std::function的使用方法和例程:
1. 使用函数指针
```cpp
#include <iostream>
#include <functional>
int add(int a, int b) {
return a + b;}
int main() {
std::function<int(int, int)> f = add;
std::cout << f(1, 2) << std::endl; // 输出 3
return 0;
}
```
2. 使用成员函数指针
```cpp
#include <iostream>
#include <functional>
class MyClass {
public:
int multiply(int a, int b) {
return a * b;
}
};
int main() {
MyClass obj;
std::function<int(MyClass*, int, int)> f = &MyClass::multiply;
std::cout << f(&obj, 2, 3) << std::endl; // 输出 6
return 0;
}
```
3. 使用lambda表达式
```cpp
#include <iostream>
#include <functional>
int main() {
std::function<int(int, int)> f = [](int a, int b) {
return a - b;
};
std::cout << f(5, 3) << std::endl; // 输出 2
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)