bind1st和bind2nd只能用于二元函数对象
c++11 bind绑定器 返回的结果还是个函数对象

std::bind函数定义在头文件functional中,是一个函数模板,它就像一个函数适配器,接受一个可调用对象(callable object),生成一个新的可调用对象来“适应”原对象的参数列表。一般而言,我们用它可以把一个原本接收N个参数的函数fn,通过绑定一些参数,返回一个接收M个(M可以大于N,但这么做没什么意义)参数的新函数。同时,使用std::bind函数还可以实现参数顺序调整等操作

bind简单使用

#include <iostream>
#include <string>
#include <functional>
using namespace std;
void SayHello(string mess) {
	cout << "SayHello(string mess)" << endl;
}
int Play(int mess) {
	cout << "int Play(int mess)=" << mess << endl;
	return mess;
}
void Say(string mess) {
	cout << "int SayHello(int mess)=" << mess << endl;
}
class student {
public:
	int show(int x) {
		cout << "Student int show(int x)" << endl;
		return x;
	}
};
int main() {
	bind(SayHello, "Hello")();
       //占位符
	bind(&student::show, student(), placeholders::_1)(200);
	//使用fuction 接受bind返回值
	function<int (int )> f= bind(Play, placeholders::_1);
	f(500);
        f(400);
        f(300);
	system("pause");
	return 0;
}

自己实现bind

#include <iostream>
#include <string>
#include <functional>
using namespace std;
template<typename T>
class MyFunction {};
template<typename R, typename A>
//接受函数,接受1个函数参数
class MyFunction<R(A)> {
public:
	//定义函数指针 返回值R ,1个函数参数
	typedef R(*pfunction)(A);
	MyFunction(pfunction  _function , A _args) : function(_function), args(_args) {}
	R operator()() {
		return (*function)(args);
	}
private:
	pfunction  function;
	A args;
};
//R 是函数, A 是绑定的参数
template<typename R,typename A>
MyFunction<R> mybind(R _function,  A _args) {
	//返回函数对象
	return  MyFunction<R>(_function, _args);
}
int SayHello(int mess) {
	cout << "int SayHello(int mess)=" << mess << endl;
	return mess;
}
int main() {
	MyFunction<int(int)> r = mybind<int(int),int>(SayHello,100);
	r();
	system("pause");
	return 0;
}

bind 和function 结合实现简单线程池

#include <iostream>
#include <vector>
#include<functional>
#include<Thread>
using namespace std;
class MyThread {
public:
	MyThread(function<void()> _f):f(_f) {}
	thread start() {
		return thread(f);
	}
private:
	function<void()> f;
};
class ThreadPool {
public:
	ThreadPool() {}
	~ThreadPool() {
		for (int i = 0; i < _pthreadPool.size(); ++i) {
			delete _pthreadPool[i];
		}
	}
	void start(int size=10) {
		for (int i = 0; i < size; i++) {
			function<void()> f = bind(&ThreadPool::runThreadId,this, i);
			MyThread  * pThread   =new MyThread (f);
			_pthreadPool.push_back(pThread);			
		}//end for
		for (int i = 0; i < size; i++) {
			_threadHandler.push_back(_pthreadPool[i]->start());
		}//end for
		for (thread & t : _threadHandler) {
			t.join();
		}
	}
	void runThreadId(int id) {
		cout << "runThreadId " << id << endl;
	}
private:
	vector<MyThread *> _pthreadPool;
	vector<thread    > _threadHandler;
};
int main() {
	ThreadPool tp;
	tp.start();
	system("pause");
	return 0;
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。