這次要講的是:c++11中的bind和function std::function 它是函數(shù)、函數(shù)對象、函數(shù)指針、和成員函數(shù)的包裝器,可以容納任何類型的函數(shù)對象,函數(shù)指針,引用函數(shù),成員函數(shù)的指針。
void G(); struct A { void H(){} }; std::function<void()> f = G; //全局函數(shù) A a; std::function<void()> f 1= std::bind(&A::H, a); //成員函數(shù)
struct A { A(std::function<void()>& f):m_callback(f) void Notify() { m_callback();//回調(diào)到上層 } std::function<void()> m_callback; }
void Foo(int x, std::function<void(int)>& f) { if(x%2==0) f(x); } void G(int x) { cout<<x<<endl; } void H(int x) { cout<<x+2<<endl; } void TestFoo() { auto f = std::bind(G, std::placeholders::_1); Foo(4, f); //在Foo函數(shù)外面更改f的行為 f = std::bind(H, std::placeholders::_1); Foo(4, f); } std::bind綁定器
void H(int a); //綁定全局函數(shù) auto f11 = std::bind(H, std::placeholders::_1); auto的類型實際上是std::function<void(int)> //綁定帶參數(shù)的成員函數(shù) std::function<void (char*, int)> f = std::bind(&ReadHandler::ConnectPreProcess, this, std::placeholders::_1, std::placeholders::_1); //三元函數(shù)轉(zhuǎn)換成一元函數(shù) int f(int, char, double); // 綁定f()函數(shù)調(diào)用的第二個和第三個參數(shù), // 返回一個新的函數(shù)對象為ff,它只帶有一個int類型的參數(shù) auto ff = bind(f, _1, ‘c’, 1.2); int x = ff(7);
其實bind簡化和增強(qiáng)了之前標(biāo)準(zhǔn)庫中bind1st和bind2nd,它完全可以替代bind1s和bind2st,并且能組合函數(shù)。我們知道bind1st和bind2nd將一個二元算子轉(zhuǎn)換成一個一元算子。 //查找元素值大于10的元素的個數(shù) int count = count_if(coll.begin(), coll.end(), std::bind1st(less<int>(), 10)); //查找元素之小于10的元素 int count = count_if(coll.begin(), coll.end(), std::bind2nd(less<int>(), 10)); 本質(zhì)上是對一個二元函數(shù)less<int>的調(diào)用,但是它卻要分別用bind1st和bind2nd,而且還要想想到底是用bind1st還是bind2nd,用起來感覺不方便?,F(xiàn)在用bind,就可以以統(tǒng)一的方式去實現(xiàn)了。 //查找元素值大于10的元素的個數(shù) int count = count_if(coll.begin(), coll.end(), bind(less<int>(), 10, _1)); //查找元素之小于10的元素 int count = count_if(coll.begin(), coll.end(), bind(less<int>(), _1, 10)); 這樣我就不用關(guān)心到底是用bind1st還是bind2nd了,只要用bind就都搞定了。
bind的還有一個強(qiáng)大之處就是函數(shù)組合。假設(shè)我們要找出集合中大于5小于10的元素個數(shù)怎么做呢?我們需要一個邏輯與才能做到類似于: std::bind(std::logical_and<bool>(),_1,_2);
然后,我們需要另一個謂詞來回答 _1 是否大于5。 std::bind(std::greater<int>(),_1,5); 然后,我們還需要另一個謂詞來回答 _1 是否小于等于10。 std::bind(std::less_equal<int>(),_1,10); 最后,我們需要把它們兩個用邏輯與合起來,就象這樣: //查找集合中大于5小于10的元素個數(shù) auto f = bind(std::logical_and<bool>(), bind(std::greater<int>(),_1,5), bind(std::less_equal<int>(),_1,10)); int count = count_if(coll.begin(), coll.end(), f); c++11中推出function是為了泛化函數(shù)對象,函數(shù)指針,引用函數(shù),成員函數(shù)的指針,讓我們可以按更統(tǒng)一的方式寫出更加泛化的代碼;推出bind是為了替換和增強(qiáng)之前標(biāo)準(zhǔn)庫的bind1st和bind2st,讓我們的用起來更方便! c++11 boost技術(shù)交流群:296561497,歡迎大家來交流技術(shù)。 |
|