std::bind的使用样例
时间: 2023-10-19 20:29:38 浏览: 49
`std::bind` 是 C++11 引入的一个函数模板,用于绑定函数或成员函数的参数。下面是一个 `std::bind` 的使用样例:
```c++
#include <iostream>
#include <functional>
void print(int a, int b, int c) {
std::cout << "a=" << a << ", b=" << b << ", c=" << c << std::endl;
}
class A {
public:
void print(int a, int b, int c) {
std::cout << "a=" << a << ", b=" << b << ", c=" << c << std::endl;
}
};
int main() {
auto f1 = std::bind(&print, 1, 2, 3);
f1();
auto f2 = std::bind(&A::print, A(), 4, 5, 6);
f2();
return 0;
}
```
上述代码中,`std::bind` 绑定了函数 `print` 和类 `A` 的成员函数 `print` 的前三个参数,并生成了两个可调用对象 `f1` 和 `f2`。`f1` 调用 `print(1, 2, 3)`,`f2` 调用 `A::print(4, 5, 6)`。可以看出,`std::bind` 可以方便地绑定函数或成员函数的部分参数,生成新的可调用对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)