cpp11的 std::function
时间: 2023-05-30 11:04:51 浏览: 87
std::function是一个通用的函数封装器,它可以存储、复制、调用任何可调用对象(函数、函数指针、成员函数指针、Lambda表达式等),并且可以根据需要自动调整存储空间。
使用std::function需要包含头文件<functional>。
std::function的基本语法如下:
```cpp
std::function<返回值类型(参数类型)> 函数对象名;
```
std::function的使用示例:
```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
f = [](int a, int b) { return a - b; };
std::cout << f(3, 2) << std::endl; // 输出:1
return 0;
}
```
在以上示例中,我们首先定义了一个add函数用来计算两个整数的和。然后,我们定义了一个std::function对象f,它可以存储两个整数作为参数并返回一个整数的可调用对象。接着,我们将add函数作为f的初始值,并通过调用f来计算1 + 2并输出结果。然后,我们将一个Lambda表达式作为f的新值,并通过调用f来计算3 - 2并输出结果。
相关问题
std::function.swap
std::function.swap 是 C++ 标准库中 std::function 类的一个成员函数,用于交换两个 std::function 对象的内容。std::function 是一个通用的函数封装器,可以包装任意可调用对象(函数、函数指针、成员函数指针、lambda 表达式等),并提供一致的调用接口。
使用 std::function.swap 可以方便地交换两个 std::function 对象的内容,实现方式如下:
```cpp
void swap(std::function& other) noexcept;
```
其中,`other` 是另一个 std::function 对象,通过调用 swap 函数,可以将当前对象和 `other` 对象的内容进行交换。
使用示例:
```cpp
std::function<int(int)> func1 = [](int x) { return x * 2; };
std::function<int(int)> func2 = [](int x) { return x * 3; };
func1.swap(func2);
int result1 = func1(5); // 调用 func2,返回 5 * 3 = 15
int result2 = func2(5); // 调用 func1,返回 5 * 2 = 10
```
注意,std::function.swap 只交换两个对象的内容,并不会影响对象的类型或其他属性。
std::function
std::function是C++11引入的一个函数对象封装类模板,它可以用来存储、复制和调用任何可调用对象(函数、函数指针、成员函数指针、lambda表达式等)。它提供了一种通用的方式来处理不同类型的可调用对象,使得代码更加灵活和可扩展。
std::function的定义如下:
```cpp
template<class R, class... Args>
class function<R(Args...)>;
```
其中,R表示返回值类型,Args表示参数类型。
std::function可以通过以下几种方式来使用:
1. 将函数指针或者成员函数指针赋值给std::function对象;
2. 使用lambda表达式创建一个可调用对象,并将其赋值给std::function对象;
3. 将一个可调用对象(如函数对象)赋值给std::function对象。
通过std::function,我们可以实现函数回调、事件处理等功能,使得代码更加灵活和可复用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.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)