项目前置知识技术点功能用例:C++11中的bind
C++11中的bind:
bind (Fn&& fn, Args&&... args);
官方文档对于bind接口的概述解释:Bind function arguments
我们可以将bind接口看做是一个通用的函数适配器,他接受一个函数对象,以及函数的各项参数,然后返回一个新的函数对象,但是这个函数对象的参数已经被绑定为设置的参数。运行的时候相当于总是调用传入固定参数的原函数。
但是如果进行绑定的时候,给与的参数为 'std::placeholders::_1,_2...’ 则相当于为新适配生成的函数对象的调用预留一个参数进行传递。
#include <iostream>
#include <functional>
#include <unistd.h>
class Test {
public:Test() { std::cout << "构造" << std::endl; }~Test() { std::cout << "析构" << std::endl; }
};void del(const Test *t, int num) {std::cout << num << std::endl;delete t;
}int main()
{Test *t = new Test;/*bind作⽤也可以简单理解为给⼀个函数绑定好参数,然后返回⼀个参数已经设定好或者预留好的函数,可以在合适的时候进⾏调⽤*//*⽐如,del函数,要求有两个参数,⼀个Test*, ⼀个int,⽽这⾥,想要基于del函数,适配⽣成⼀个新的函数,这个函数固定第1个参数传递t变量,第⼆个参数预留出来,在调⽤的时候进⾏设置*/std::function<void(int)> cb = std::bind(del, t, std::placeholders::_1);cb(10); while(1) sleep(1);return 0;
}
终端运行结果:
[dev@localhost example]$ g++ -std=c++11 bind.cpp -o bind
[dev@localhost example]$ ./bind
构造
10
析构^C
基于bind的作用,当我们在设计⼀些线程池,或者任务池的时候,就可以将将任务池中的任务设置为函数类型,函数的参数由添加任务者直接使用bind进行适配绑定设置,而任务池中的任务被处理,只需要取出⼀个个的函数进行执行即可。
这样做有个好处就是,这种任务池在设计的时候,不用考虑都有哪些任务处理方式了,处理函数该如何设计,有多少个什么样的参数,这些都不用考虑了,降低了代码之间的耦合度。
#include <iostream>
#include <string>
#include <vector>
#include <functional>void print(const std::string &str) {std::cout << str << std::endl;
}
int main()
{using Functor = std::function<void()>;std::vector<Functor> task_pool;task_pool.push_back(std::bind(print, "张三"));task_pool.push_back(std::bind(print, "你好"));task_pool.push_back(std::bind(print, "我是"));task_pool.push_back(std::bind(print, "好学⽣"));for (auto &functor : task_pool) {functor();}return 0;
}
终端操作及结果:
[dev@localhost example]$ g++ -std=c++11 bind.cpp -o bind
[dev@localhost example]$ ./bind
张三
你好
我是
好学⽣
[dev@localhost example]$
本篇文章介绍了c++11std::bind函数的相关使用,以及它对于后面我们项目里边实现任务池线程池的重要性。欢迎留言交流!