bind1st和bind2nd只能用於二元函數對象 c++11 bind綁定器 返回的結果還是個函數對象 std::bind函數定義在頭文件functional中,是一個函數模板,它就像一個函數適配器,接受一個可調用對象(callable object),生成一個新的可調用對象來“適應”原對象的參數 ...
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;
}