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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/539501.html
標籤:其他
下一篇:朝花夕拾-鏈表(二)
