概述
std::bind的頭文件是 <functional>;,它是一個函數適配器,接受一個可調用對象(callable object),生成一個新的可調用對象來“適應”原對象的參數列表。
函數原型
std::bind函數有兩種函數原型,定義如下:
template< class F, class... Args >
bind( F&& f, Args&&... args );
template< class R, class F, class... Args >
bind( F&& f, Args&&... args );
std::bind返回一個基於f的函數對象,其參數被綁定到args上。
f的參數要么被綁定到值,要么被綁定到placeholders(占位符,如_1, _2, ..., _n)。
std::bind將可調用對象與其參數一起進行綁定,綁定后的結果可以使用std::function保存。std::bind主要有以下兩個作用:
- 將可調用對象和其參數綁定成一個仿函數;
- 只綁定部分參數,減少可調用對象傳入的參數。
1 std::bind綁定普通函數
double callableFunc (double x, double y) {return x/y;}
auto NewCallable = std::bind (callableFunc, std::placeholders::_1,2);
std::cout << NewCallable (10) << std::endl;
- bind的第一個參數是函數名,普通函數做實參時,會隱式轉換成函數指針。因此std::bind(callableFunc,_1,2)等價於std::bind (&callableFunc,_1,2);
- _1表示占位符,位於<functional>中,std::placeholders::_1;
- 第一個參數被占位符占用,表示這個參數以調用時傳入的參數為准,在這里調用NewCallable時,給它傳入了10,其實就想到於調用callableFunc(10,2);
2 std::bind綁定一個成員函數
class Base
{
void display_sum(int a1, int a2) {
std::cout << a1 + a2 << '\n';
}
int m_data = 30;
};
int main()
{
Base base;
auto newiFunc = std::bind(&Base::display_sum, &base, 100, std::placeholders::_1);
f(20);
}
- bind綁定類成員函數時,第一個參數表示對象的成員函數的指針,第二個參數表示對象的地址。
- 必須顯示的指定&Base::diplay_sum,因為編譯器不會將對象的成員函數隱式轉換成函數指針,所以必須在Base::display_sum前添加&;
- 使用對象成員函數的指針時,必須要知道該指針屬於哪個對象,因此第二個參數為對象的地址 &base;
3 綁定一個引用參數
默認情況下,bind的那些不是占位符的參數被拷貝到bind返回的可調用對象中。但是,與lambda類似,有時對有些綁定的參數希望以引用的方式傳遞,或是要綁定參數的類型無法拷貝。
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std::placeholders;
using namespace std;
ostream & printInfo(ostream &os, const string& s, char c)
{
os << s << c;
return os;
}
int main()
{
vector<string> words{"welcome", "to", "C++11"};
ostringstream os;
char c = ' ';
for_each(words.begin(), words.end(),
[&os, c](const string & s){os << s << c;} );
cout << os.str() << endl;
ostringstream os1;
// ostream不能拷貝,若希望傳遞給bind一個對象,
// 而不拷貝它,就必須使用標准庫提供的ref函數
for_each(words.begin(), words.end(),
bind(printInfo, ref(os1), _1, c));
cout << os1.str() << endl;
}