前言
本文介绍了bind绑定器和function函数对象,基于施磊老师的C++课程。
一、模板的完全特例化和部分特例化
还有模板的实参推演,这里省略。
二、function的实现原理
function的实现本质上就是定义了一个类首先接收函数指针类型,然后封装了一个()运算符重载函数,在这个运算符重载函数中对之前接收的函数指针进行调用。这是基于模板的实参推演,而为了推演任意的函数,使用了可变参模板:
#include <iostream>
#include <string>
using namespace std;
template<typename T>
class myfunction {};
template<typename R, typename... args>
class myfunction<R(args...)>
{
public:
using PFUNC = R(*)(args...);
myfunction(PFUNC p) : pfunc(p) {}
R operator() (args... arg) {
return pfunc(arg...);
}
private:
PFUNC pfunc;
};
int sum(int a, int b) {
return a + b;
}
void hello(string str) {
cout << str << endl;
}
int main()
{
myfunction<void(string)> f(hello);
f("hello world!");
myfunction<int(int, int)> p(sum);
cout << p(10, 20) << endl;
return 0;
}
注意需要先定义一个类模板,在通过模板的特例化定义带有参数的版本。
三、bind和function实现线程池
bind返回的也是函数对象,注意参数占位符的运用:

下面使用bind和function实现的线程池:
#include <iostream>
#include <functional>
#include <vector>
#include <thread>
using namespace std;
class Thread
{
public:
Thread(function<void()> func) : _func(func) {}
thread start() {
thread t(_func);
return t;
}
private:
function<void()> _func;
};
class ThreadPool
{
public:
ThreadPool() {}
~ThreadPool() {
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;
void runInThread(int id) {
cout << "call runInThread id: " << id << endl;
}
};
int main()
{
ThreadPool pool;
pool.startPool(10);
return 0;
}
四、lambda表达式的实现原理
lambda表达式本质就是函数对象的简化版本

3990

被折叠的 条评论
为什么被折叠?



