std::bind传惨
时间: 2024-05-10 19:12:42 浏览: 7
std::bind 是 C++11 中的一个函数模板,用于将一个可调用对象(函数、函数指针、成员函数指针等)与其参数绑定。通过 std::bind 可以在调用时只传递部分参数,剩余参数可以在稍后调用时传递或者默认使用。
std::bind 的语法如下:
```c++
template< class F, class... Args >
constexpr /*unspecified*/ bind( F&& f, Args&&... args );
```
其中 F 表示可调用对象的类型,Args 表示参数的类型。使用时需要将可调用对象和其参数作为 std::bind 的参数传递进去,然后可以通过调用返回的绑定对象来执行该可调用对象。例如:
```c++
#include <iostream>
#include <functional>
void foo(int a, int b, int c)
{
std::cout << a << "+" << b << "+" << c << "=" << a + b + c << std::endl;
}
int main()
{
auto f = std::bind(foo, 1, std::placeholders::_2, 3);
f(2);
return 0;
}
```
上面的代码中,通过 std::bind 将函数 foo 的第一个参数绑定为 1,第三个参数绑定为 3,第二个参数使用占位符 std::placeholders::_2 表示稍后调用 f 时再传递。然后调用返回的 f 对象并传递第二个参数为 2,最终输出结果为 "1+2+3=6"。