前言
在学习中,有句
bind
相关的代码看了一天终于懂了意思。。记录下
1. 问题引入
当时我看的部分是muduo
的简单使用,卡在了这两句上
//给服务器注册用户连接的创建和断开回调
_server.setConnectionCallback(std::bind(&ChatServer::onConnection, this, _1));
//给服务器注册用户读写事件回调
_server.setMessageCallback(std::bind(&ChatServer::onMessage, this, _1, _2, _3));
我直接看懵逼了,人傻在了那里,原来自己在知识面前一直是一粒微不足道的灰尘。在我找了一天资料后终于懂了这句话的意思后,那一刻!很有成就感!(好的吧,先忽略下本菜鸡的菜鸡技术)
先写下我当时的想法。关于bind
,我对其的印象是将二元函数变成一元函数,可以和greater
/less
一起用在find_if
函数中。于是我百思不得其解,咦?为什么这里只有_1
,没有写到_1
的参数呢? 下面我将围绕这个疑问从以下几个方面一层层地回答我当时的疑问。#1 bind 的历史演变 #2 bind的使用 #3 function # 4举例
2. bind 的历史演变
在介绍bind
之前必须要介绍下bind1st 和 bind2nd
在 STL 中有一个 find_if
算法,它的原理应该就是线性扫描一遍,找到符合条件的就返回相应的迭代器。
将find_if
的实现扒出来看看:
template <class _InIt, class _Pr>
_NODISCARD _CONSTEXPR20 _InIt find_if(_InIt _First, const _InIt _Last, _Pr _Pred) { // find first satisfying _Pred
_Adl_verify_range(_First, _Last);
auto _UFirst = _Get_unwrapped(_First);
const auto _ULast = _Get_unwrapped(_Last);
for (; _UFirst != _ULast; ++_UFirst) {
if (_Pred(*_UFirst)) {
break;
}
}
_Seek_wrapped(_First, _UFirst);
return _First;
}
观察到和 _Pred
相关的语句是
if (_Pred(*_UFirst)) {
break;
}
可以看到 _Pred
只有一个参数,所以传入 find_if
的函数只能是只有一个变量的。
再把 greater<T>()
打开看看如何?
template <class _Ty = void>
struct greater {
_CXX17_DEPRECATE_ADAPTOR_TYPEDEFS typedef _Ty _FIRST_ARGUMENT_TYPE_NAME;
_CXX17_DEPRECATE_ADAPTOR_TYPEDEFS typedef _Ty _SECOND_ARGUMENT_TYPE_NAME;
_CXX17_DEPRECATE_ADAPTOR_TYPEDEFS typedef bool _RESULT_TYPE_NAME;
constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const {
return _Left > _Right;
}
};
可以看到 greater
的实现需要两个参数的传入。那么问题来了:如何将 greater
变成只需要传入一个参数的函数呢?
C++提供了 bind1st 和 bind2nd
。将二元函数对象变为一元函数对象。
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <ctime>
using namespace std;
template<typename Container>
void showContainer(Container& con)
{
typename Container::iterator it = con.begin(); //说明是类型, 不是变量
for (; it != con.end(); it++)
{
cout << *it << ' ';
}
cout << endl;
}
int main()
{
vector<int> vec;
srand(time(nullptr));
for (int i = 0; i < 20; i++)
{
vec.push_back(rand() % 100 + 1);
}
//二元函数对象
sort(vec.begin(), vec.end(), greater<int>());
showContainer(vec);
//把70按序插入到容器中 => 找第一个小于70的数字
//find_if 需要一个一元函数对象
//绑定器 + 二元函数对象 => 一元函数对象
auto it = find_if(vec.begin(), vec.end(),
bind1st(greater<int>(), 70));
auto it2 = find_if(vec.begin(), vec.end(),
bind2nd(less<int>(), 70));
if (it2 != vec.end()) {
vec.insert(it2, 70);
}
showContainer(vec);
return 0;
}
为了探究bind1st 和 bind2nd
的实现发生了什么,我们大可实现一下。
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <ctime>
using namespace std;
//打印容器的内容
template<typename Container>
void showContainer(Container& con)
{
typename Container::iterator it = con.begin(); //说明是类型, 不是变量
for (; it != con.end(); it++)
{
cout << *it << ' ';
}
cout << endl;
}
//comp得接收一元的 底层调用_mybind1st的运算符重载
template<typename Iterator, typename Compare>
Iterator my_find_if(Iterator first, Iterator last, Compare comp)
{
for (; first != last; ++first)
{
if (comp(*first)) //comp.operator()(*first)
{
return first;
}
}
return last;
}
template<typename Compare, typename T>
class _mybind1st
{
public:
_mybind1st(Compare comp, T val)
:_comp(comp), _val(val)
{}
//这里是my_find_if的Compare
bool operator()(const T& second)
{
return _comp(_val, second); //底层还是greater
}
private:
Compare _comp;
T _val;
};
template<typename Compare, typename T>
_mybind1st<Compare, T> mybind1st(Compare comp, const T& val)
{
//函数模板的好处: 可以进行类型的推演
return _mybind1st<Compare, T>(comp, val);
}
/*
bind2nd实现
*/
template<typename Compare, typename T>
class _mybind2nd
{
public:
_mybind2nd(Compare comp, T val)
:_comp(comp), _val(val)
{}
bool operator()(const T& first)
{
return _comp(first, _val); //底层还是less
}
private:
Compare _comp;
T _val;
};
template<typename Compare, typename T>
_mybind2nd<Compare, T> mybind2nd(Compare comp, const T& val)
{
return _mybind2nd<Compare, T>(comp, val);
}
int main()
{
vector<int> vec;
srand(time(nullptr));
for (int i = 0; i < 20; i++)
{
vec.push_back(rand() % 100 + 1);
}
//二元函数对象
sort(vec.begin(), vec.end(), greater<int>());
showContainer(vec);
//把70按序插入到容器中 => 找第一个小于70的数字
//find_if 需要一个一元函数对象
//绑定器 + 二元函数对象 => 一元函数对象
auto it2 = my_find_if(vec.begin(), vec.end(),
mybind2nd(less<int>(), 70));
if (it2 != vec.end()) {
vec.insert(it2, 70);
}
showContainer(vec);
return 0;
}
但是 bind1st 和 bind2nd
的使用也有其局限性,它只能将二元转一元,如果此时来了三元呢?如何将三元转一元?别急,bind
登场了。
3. 使用 bind
了解一个东西的原理之前,我们可以先简单地用用。
以下提供两个 bind
的简单例子:
绑定一个普通函数和函数指针
#include <iostream>
#include <functional>
#include <cstdio>
using namespace std;
using namespace placeholders;
void fun(int a, int b, int c, int d, int e) {
printf("%d %d %d %d %d\n", a, b ,c, d, e);
}
int main() {
int x = 1, y = 2, z = 3;
auto g = bind(&fun, x, y, _2, z, _1); //第一个参数&可省略 但最好写成&fun
g(11, 22); // 1 2 22 3 11
}
绑定一个类成员对象
#include <iostream>
#include <functional>
#include <cstdio>
using namespace std;
using namespace placeholders;
class Test {
public:
void func(int a, int b, int c, int d, int e)
{
printf("%d %d %d %d %d\n", a, b, c, d, e);
}
};
int main() {
//当参数为类内非静态成员函数时,第一个参数必须使用&符号。
auto f = bind(&Test::func, Test(), _1, 12, _3, 5, _2);
f(10, 6, 7);
f.operator()(10, 6, 7);
}
//都输出 10 12 7 5 6
其实到了这个地方我的疑惑已经快解决了,不知诸位有没有注意到这一句
auto f = bind(&Test::func, Test(), _1, 12, _3, 5, _2);
f
是什么?为什么 f
可以像函数一样调用?(函数名后面加小括号才能实现函数功能)
此时答案开始明了了:我们有理由相信 bind
生成的是一个类似函数名的东西,它可以调用函数。
4. function 简要介绍
function
是 C++ 特有的,它的功能约等于 C 的函数指针。
和普通函数一起使用
void hello1()
{
cout << "Hello world" << endl;
}
void hello2(string str)
{
cout << str << endl;
}
int sum(int a, int b)
{
return a + b;
}
int main()
{
//用一个函数类型实例化函数类型
function<void()> func1(hello1);
func1(); //func1.operator()
function<void(string)> func2(hello2);
func2("fun2");
function<int(int, int)> func3(sum);
cout << func3(3, 4) << endl;
//operator()
function<int(int, int)> func4 = [](int a, int b)->int {return a + b; };
cout << func4(100, 200) << endl;
return 0;
}
和类一起使用
class Test
{
public: //必须依赖一个对象 void (Test::*pfunc)(string)
void hello(string str) { cout << str << endl; }
};
/*
1. 用函数类型实例化function
2. 通过fuction调用operator()函数的时候,需要根据函数类型传入相应的参数
*/
int main()
{
function<void(Test*, string)> func5 = &Test::hello;
func5(&Test(), "call Test::hello");
return 0;
}
可以巧妙地替代 switch
void doShowAllBooks() { cout << "查看所有书籍信息" << endl; }
void doBorroe() { cout << "借书" << endl; }
void doBack() { cout << "还书" << endl; }
void doQueryBooks() { cout << "查询书籍" << endl; }
void doLoginOut() { cout << "注销" << endl; }
int main()
{
int choice = 0;
map<int, function<void()>> actionMap;
actionMap.insert({ 1, doShowAllBooks });
actionMap.insert({2, doBorroe });
actionMap.insert({3, doBack });
actionMap.insert({4, doQueryBooks });
actionMap.insert({5, doLoginOut });
for (;;)
{
cout << "--------" << endl;
cout << "1.查看所有书籍信息" << endl;
cout << "2.接书" << endl;
cout << "3.还书" << endl;
cout << "4.查询书籍" << endl;
cout << "5.注销" << endl;
cout << "--------" << endl;
cin >> choice;
auto it = actionMap.find(choice);
if (it == actionMap.end()) {
cout << "输入数字无效,重新选择" << endl;
} else {
it->second();
}
}
return 0;
}
综合应用例子
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <ctime>
#include <string>
#include <map>
#include <typeinfo>
using namespace std;
using namespace placeholders;
/*
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")();
cout << bind(sum, 10, 20)() << endl;
//方法 对象 参数
cout << bind(&Test::sum, Test(), 20, 30)() << endl;
cout << typeid(sum).name() << endl;
//参数占位符
//这个参数具体是什么我不知道 等用户来传递
cout << typeid(bind(hello, _1)("参数占位符")).name() << endl;
cout << bind(sum, _1, _2)(200, 300) << endl;
cout << typeid(bind(sum, _1, _2)(200, 300)).name() << endl;
function<void(string)> func1 = bind(hello, _1);
func1("Hello china");
func1( "Hello hubei");
return 0;
}
5. function 和 bind 实现 mini线程池
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <ctime>
#include <string>
#include <map>
#include <typeinfo>
#include <thread>
using namespace std;
using namespace placeholders;
//线程类
class Thread
{
public:
Thread(function<void()>func) :_func(func) {}
thread start()
{
thread t(_func); // _func()
return t;
}
private:
function<void()> _func;
};
//线程池类
class ThreadPool
{
public:
ThreadPool(){}
~ThreadPool()
{
//释放Thread对象占用的资源
for (int i = 0; i < _pool.size(); i++)
{
delete _pool[i];
}
}
//开启线程池
void startPool(int size)
{
for (int i = 0; i < size; i++)
{
_pool.push_back(
new Thread(bind(&ThreadPool::runInThread, this, i)));
}
for (int i = 0; i < size; i++)
{
_handler.push_back(_pool[i]->start());
}
for (thread& t : _handler)
{
t.join();
}
}
private:
vector<Thread*> _pool;
vector<thread> _handler;
//把runInThread这个成员方法充当线程函数
void runInThread(int id)
{
cout << "call runInThread id:" << id << endl;
}
};
int main()
{
ThreadPool pool;
pool.startPool(10);
}
也可以改成_1
格式
//线程类
class Thread
{
public:
Thread(function<void(int)>func, int no) :_func(func), _no(no) {}
thread start()
{
thread t(_func, _no); // _func(_no)
return t;
}
private:
function<void(int)> _func;
int _no;
};
//开启线程池
for (int i = 0; i < size; i++)
{
_pool.push_back(
new Thread(bind(&ThreadPool::runInThread, this, _1), i));
}
6. 总结
bind绑定后的类型是一个function,把private里面的函数赋值给了另一个class里的函数变量!可以在另一个class里访问我的private函数。
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <ctime>
#include <string>
#include <map>
#include <typeinfo>
using namespace std;
using namespace placeholders;
class before
{
public:
before(string s)
{
_s = s;
}
void callBack(const function<void(string)>& cb)
{
cout << "callBack" << endl;
_cb = cb;
_cb("callBack's onConnection");
}
private:
function<void(string)> _cb;
string _s;
};
class Test
{
public:
Test(string s)
:_server(s)
{
cout << "Test init" << endl;
_server.callBack(std::bind(&Test::onConnection, this, _1));
}
private:
before _server;
void onConnection(const string& t)
{
cout << t << endl;
}
};
int main()
{
Test t1("t1");
return 0;
}