C++11绑定器介绍
大约 2 分钟
C++11绑定器介绍
C++ STL的bind只能用于二元的绑定器
C++11 bind绑定器 => 返回的结果还是一个,可以。
C++11的bind和function比较:
- function可以直接将函数类型留下来。
- bind绑定器可以给函数绑定固定的参数。
#include <iostream>
#include <typeinfo>
#include <string>
#include <memory>
#include <vector>
#include <functional>
#include <thread>
using namespace std;
/*
C++11 bind绑定器 => 返回的结果还是一个函数对象
*/
void hello(string str) { cout << str << endl; }
int sum(int a, int b) { return a + b; }
class Test
{
public:
int sum(int a, int b) { return a + b; }
};
int main()
{
//bind是函数模板 可以自动推演模板类型参数
bind(hello, "hello bind!")();//bind绑定了一个"hello bind!"参数,
//返回的结果是绑定器,也就是函数对象, 需要调用它的()重载符号
cout << bind(sum, 10, 20)() << endl;
cout << bind(&Test::sum, Test(), 20, 30)() << endl;
return 0;
}
- bind是函数模板
- 返回的结果是绑定器,也就是函数对象,
绑定器问题:
- 只能使用在语句中,出了语句就不能使用了;
如何将绑定器的类型留下来?
- 综合运用function和bind。
- 定义funtion,返回值是void,有一个string形参变量的函数类型,用来记录bind绑定器绑定的结果。
- 可以通过function函数对象类型,把绑定器的类型留下来,可以重复的去使用。
参数占位符
调用的时候,用户自己传入参数!!!
参数占位符placeholders::_1
: 参数具体是什么,不知道,等待用户传递;(最多有20个占位参数)
- 因此在调用时,必须在()中传入参数;

using namespace placeholders;
int main() {
//参数占位符 绑定器出了语句,无法继续使用
//只是占位的作用,调用的时候就要传递参数了
//书写的时候使用多少个占位符,就是意味着用户调用的时候要传入几个参数
bind(hello, _1)("hello bind 2!");
cout << bind(sum, _1, _2)(200, 300) << endl;
//此处把bind返回的绑定器binder就复用起来了
function<void(string)> func1 = bind(hello, _1);
func1("hello china!");
func1("liu feng ni hao");
return 0;
}