之前项目中用到学习了一下,今天总结总结
bind生成一个仿函数,可以配接任意函数(裸函数,类成员函数,静态成员函数)指定参数传递方式个数。在需要仿函数的地方(accumulate,for_each等)超级好用
#include <iostream> #include <algorithm> #include <numeric> #include <map> #include <vector> #include <boost/bind.hpp> using namespace std; struct comp { pair<double, double> operator()(const pair<double, double>& init, double x) const { return make_pair(init.first + x, init.second + x*x); } }; class A { public: pair<double, double> sum(const pair<double, double>& init, double x) const { return make_pair(init.first + x, init.second + x*x); } }; pair<double, double> sum(const pair<double, double>& init, double x, double y, double z) { return make_pair(init.first + x + y, init.second + x*x); } pair<double, double> sum2(const pair<double, double>& init, double x, double y) { return make_pair(init.first + x + y, init.second + y*y); } int main () { vector<double> test; for(int i = 0; i < 100; ++i) { test.push_back(i); } A a; double y = 0.0; //a.sum(); A::sum(*this) //pair<double, double> re = accumulate(test.begin(), test.end(), make_pair(0, 0), comp()); //pair<double, double> re = accumulate(test.begin(), test.end(), make_pair(0, 0), boost::bind((&A::sum), &a, _1, _2)); pair<double, double> re = accumulate(test.begin(), test.end(), make_pair(0, 0), boost::bind(sum, _1, _2, y, y)); //pair<double, double> re2 = boost::bind(sum, _1, _2, y, y)(make_pair(10, 10), 10); pair<double, double> re2 = boost::bind(sum2, _1, y, _2)(make_pair(10, 10), 10); // operator+(_1, _2); cout << re2.first << " " << re2.second << endl; cout << re.first << " " << re.second << endl; return 0; }
boost多线程可以三行代码搞定。。。bind的使用使得参数传递比c语言的不知道方便多少倍
上代码
#include <iostream> #include <boost/thread/thread.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <boost/bind.hpp> using namespace std; boost::mutex mtx; void show(int i) { boost::unique_lock< boost::mutex > lock(mtx);//构造函数锁,析构函数解锁 //mtx.lock(); cout << "wangbing" << i << endl; //mtx.unlock(); } int main() { int thread_num = 8; boost::thread_group group; for(int i = 0; i < thread_num; ++i) { group.create_thread( boost::bind(show, i)); } cout << "xxxxxx" << endl; group.join_all(); return 0; }