绑定器和函数对象
函数对象我们之前以及提到了,函数对象就是类方法中有operator()运算符重载的。在使用时和函数很类似。
绑定器
在C++ STL库中有两个绑定器
绑定器 + 二元函数对象 = 一元函数对象
bind1st: operator()的第一个形参变量绑定成一个确定的值。
bind2nd:operator()的第二个形参变量绑定成一个确定的值。
但是其实在复杂的应用场景下,这两个绑定器并不能满足应用的需求,于是在C++11中从Boost库中引入了bind绑定器和function函数对象机制。
绑定器的使用
#include<vector>
#include<functional>//包含c库中所有的函数对象
#include<algorithm>///包含所有的泛型算法
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());//默认小到大
sort(vec.begin(), vec.end(), greater<int>()); // 大到小排序,greater是一个二元函数对象
//在这里我们把元素70按序插入
//找第一个小于70的元素
//用find_if带条件的查询
//他只需要从容器中拿一个对象,所以其需要的是一个一元函数对象,但是库中只有二元的
//所以使用到了绑定器
auto it1 = my_find_if(vec.begin(), vec.end(),
bind1st(greater<int>(), 70));
//找到了
if (it1 != vec.end())
{
vec.insert(it1, 70);
}
return 0;
}
- greater: a>b
- less : a<b
greater函数对象,是一个二元函数,在bind1st(greater<int>(), 70)
;中,我们将其第一个参数绑定为70,将其变为一个一元函数对象。
从容器中大到小每个数据与70比较,找到第一个小于70的,返回其迭代器。
当然我们也可以绑定less的第二个参数bind2nd(less<int>(),70)
;
绑定器的底层实现
先来看find_if函数,它需要的是一个一元函数对象comp。
template<typename Iterator, typename Compare>
Iterator my_find_if(Iterator first, Iterator last, Compare comp)
//find_iF就是遍历迭代器的元素,如果满足函数对象的运算,就返回当前元素的迭代器,不满足返回end
{
for (; first != last; ++first)
{
if (comp(*first)) // comp.operator()(*first)
{
return first;
}
}
return last;
}
那么这个一元函数对象由如何由二元函数对象实现呢?请看下面的代码。
template<typename Compare, typename T>
_mybind1st<Compare,T> mybind1st(Compare comp, const T &val)
{
//直接返回一个一元函数对象
return _mybind1st<Compare, T>(comp, val);
}
template<typename Compare, typename T>
class _mybind1st // 绑定器是函数对象的一个应用
{
public:
_mybind1st(Compare comp, T val)
:_comp(comp), _val(val)
{}
bool operator()(const T &second)
{
return _comp(_val, second); // greater
}
private:
Compare _comp;
T _val;
};
说白了,其实就是对二元函数对象的一个封装
而已。
function
function是一个函数包装器模板
,最早来自boost库。在c11标准中将其纳入标准库。该函数包装器模板可以包装任何类型的可调用元素,例如普通函数和函数对象。
function最大的作用就是保留可调用元素的类型。
void hello1()
{
cout << "hello world!" << endl;
}
void hello2(string str) // 类型void (*pfunc)(string)
{
cout << str << endl;
}
int sum(int a, int b)
{
return a + b;
}
class Test
{
public: // 必须依赖一个对象void (Test::*pfunc)(string)
void hello(string str) { cout << str << endl; }
};
然后在主函数中使用function:
function使用:function<返回值类型(参数类型)>
从function的类模板定义处,看到希望用一个函数类型实例化function
int main()
{
function<void()> func1 = hello1;
func1(); // func1.operator()() => hello1()
function<void(string)> func2 = hello2;
func2("hello hello2!"); // func2.operator()(string str) => hello2(str)
function<int(int, int)> func3 = sum;
cout<<func3(20, 30)<<endl;
// operator()
function<int(int, int)> func4 = [](int a, int b)->int {return a + b; };
cout << func4(100, 200) << endl;
function<void(Test*, string)> func5 = &Test::hello;
func5(&Test(), "call Test::hello!");
return 0;
}
- 其中
fun4
直接对lambda表达式进行了一个封装,使其能够达到和sum函数等同的效果。 - func5由于在类中所以要多传入一个Test*来代替类中的this指针。
注意
:
- 用函数类型实例化function;
- 通过function调用相应的operator()函数,需要根据函数传入相应参数。
所以上述的操作在干嘛?为什么不直接调用函数呢?
再来看下面的例子:
void doShowAllBooks() { cout << "查看所有书籍信息" << endl; }
void doBorrow() { cout << "借书" << endl; }
void doBack() { cout << "还书" << endl; }
void doQueryBooks() { cout << "查询书籍" << endl; }
void doLoginOut() { cout << "注销" << endl; }
int main()
{
int choice = 0;
// C的函数指针
map<int, function<void()>> actionMap;
actionMap.insert({ 1, doShowAllBooks }); // insert(make_pair(xx,xx));
actionMap.insert({ 2, doBorrow });
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;
cout << "请选择:";
cin >> choice;
//接下来很多人可能会想到switch,但是其实用switch的话,代码就无法闭合,无法做到开闭原则
auto it = actionMap.find(choice); // map pair first second
if (it == actionMap.end())
{
cout << "输入数字无效,重新选择!" << endl;
}
else
{
it->second();
}
return 0;
}
而且function能很好的避免以前c++遍地都是类的局面。其实现函数对象机制更能使得编译器实现内联调用,减少函数调用开销。
function的实现原理
//R为返回值类型,A是传入的参数类型
template<typename R, typename... A>
class myfunction<R(A...)>
{
public:
using PFUNC = R(*)(A...);
myfunction(PFUNC pfunc) :_pfunc(pfunc) {}
R operator()(A... arg)
{
return _pfunc(arg...); // hello(arg)
}
private:
PFUNC _pfunc;
};
利用template的强大机制,用...
表示多个传入的参数。,避免了因为参数的个数不同重写多个myfunction。
就是这样:
template<typename R, typename A1>
class myfunction<R(A1)>
{
public:
using PFUNC = R(*)(A1);
myfunction(PFUNC pfunc) :_pfunc(pfunc) {}
R operator()(A1 arg)
{
return _pfunc(arg); // hello(arg)
}
private:
PFUNC _pfunc;
};
template<typename R, typename A1, typename A2>
class myfunction<R(A1, A2)>
{
public:
using PFUNC = R(*)(A1, A2);
myfunction(PFUNC pfunc) :_pfunc(pfunc) {}
R operator()(A1 arg1, A2 arg2)
{
return _pfunc(arg1, arg2); // hello(arg)
}
private:
PFUNC _pfunc;
};
bind
bind1st和bind2nd在STL中主要用于二元函数对象,将其中的一元绑定成一个固定的量,成为一元函数变量。绑定器返回的结果仍然是一个函数对象。
在C++11标准中,这两位因为不够灵活,所以已经被bind所取代。
bind起源于非标准boost库,在c++11标准中正式纳入标准库,其更加灵活,最多可以绑定20个函数对象的参数。
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!")()//result:print:hello bind!
cout << bind(sum, 10, 20)() << endl;//result:print:30
cout << bind(&Test::sum, Test(), 20, 30)() << endl;//result:print:50
// 参数占位符 绑定器出了语句,无法继续使用,需要调用时由用户自己传递
bind(hello, _1)("hello bind 2!");
cout << bind(sum, _1, _2)(200, 300) << endl;//result:print:500
return 0;
}
在语句bind(hello, "hello bind!")()
;中,bind将“hello bind!”绑定至hello的string类型参数,并返回一个函数对象,调用这个函数对象的operator()函数,完成打印字符串的过程。
在语句bind(hello, _1)("hello bind 2!")
;中的_1
是名称空间 placeholders中的,用法placeholder::_1
。此为参数占位符,代表hello的第一个参数等待用户输入。在本例中将参数“hello bind 2!
”传递给operator()函数完成调用。
用function实现对bind绑定的函数对象的类型保留
bind有个缺点:bind无法保存它所绑定过的函数对象!所以就需要function和它进行配合。
int main()
{
//此处就把bind返回的绑定器复用起来了
function<void(string)> func1 = bind(hello, _1);
func1("hello china!");
func1("hello shan xi!");
func1("hello si chuan!");
return 0;
}
bind和function实现线程池
线程类
// 线程类
class Thread
{
public:
Thread(function<void(int)> func, int no) :_func(func), _no(no) {}
//这里需要包含头文件#include<thread>
thread start()
{
//定义线程t执行func函数
thread t(_func, _no); // _func(_no)
return t;
}
private:
function<void(int)> _func;//接收绑定器返回的函数对象
int _no;//线程编号
};
线程池类
线程池类
class ThreadPool
{
public:
ThreadPool() {}
~ThreadPool()
{
// 这里是指针,所以不能依靠vector析构自动析构,得手动释放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, _1), 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这个成员方法充当线程函数 thread pthread_create
void runInThread(int id)
{
cout << "call runInThread! id:" << id << endl;
}
};
int main()
{
ThreadPool pool;
pool.startPool(10);//创建10个线程
return 0;
}
#endif