std::bind()的各个参数是什么
时间: 2023-05-17 08:02:43 浏览: 53
std::bind() 的各个参数是:第一个参数是函数指针或可调用对象,后面的参数是该函数或可调用对象的参数。std::bind() 返回一个可调用对象,该对象可以在稍后的时间点调用原始函数或可调用对象,并将绑定的参数传递给它。
相关问题
std::bind是什么
std::bind是C++11中的一个函数模板,它可以将一个可调用对象(函数、函数指针、成员函数、成员函数指针等)和其参数绑定起来,生成一个新的可调用对象。这个新的可调用对象可以在后续的调用中直接使用,而不需要再传递参数。std::bind的语法如下:
```c++
template<class F, class... Args>
std::bind(F&& f, Args&&... args);
```
其中,F表示要绑定的可调用对象,Args表示要绑定的参数。std::bind返回一个新的可调用对象,它的参数个数和类型由原来的可调用对象和绑定的参数决定。
举个例子,假设有一个函数:
```c++
void foo(int a, int b, int c);
```
我们可以使用std::bind将它的第一个参数绑定为1,第二个参数绑定为2,生成一个新的可调用对象:
```c++
auto new_foo = std::bind(foo, 1, 2, std::placeholders::_1);
```
这个新的可调用对象可以像原来的函数一样调用,只需要传递最后一个参数即可:
```c++
new_foo(3); // 相当于调用 foo(1, 2, 3);
```
std::bind什么意思
std::bind是C++11标准库中的一个函数模板,用于将函数和其参数绑定到一个函数对象上。这个函数对象可以在稍后的时间点上被调用,就像调用原始函数一样。std::bind的返回类型是一个未指定类型T的函数对象,这个类型T满足以下条件: std::is_bind_expression::value == true。在使用std::bind时,第一个参数是函数名或函数指针,后面的参数是函数的参数,可以使用占位符_1、_2、_3等来表示参数的位置,也可以直接传入参数值。下面是一个std::bind绑定普通函数的例子:
```c++
#include <iostream>
#include <functional> //for std::bind
using namespace std;
double my_divide (double x, double y) {return x/y;}
int main() {
using namespace std::placeholders; //for _1
auto fn_half = std::bind (my_divide,_1,2);
std::cout << fn_half(10) << '\n'; // 输出:5
return 0;
}
```
在这个例子中,我们使用std::bind将my_divide函数和参数2绑定到一个函数对象fn_half上,然后调用fn_half(10)就相当于调用my_divide(10, 2),输出结果为5。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)