Lambda表達式:代替std::bind的絕佳方法
lambda表達式使得函數(shù)指針有了更靈活的使用方法,但是有些時候,對于大型的函數(shù),還是不建議用lambda表達式,誰也不想在函數(shù)里又看到一段長長的函數(shù)。
Lambda表達式的用法在:C++11 lambda表達式在for_each和transform算法下的使用已經(jīng)進行了介紹。另外我在另一篇文章利用C++11的function和bind功能,實現(xiàn)QStandardItemModel的通用遍歷函數(shù)里使用了std::bind功能,這個函數(shù)是為了把一個多變量的函數(shù)指針轉(zhuǎn)變?yōu)橐粋€指定變量的函數(shù)指針
例如有個函數(shù)如:
void?fun1(int?a)
但實際上你可能想要傳入的函數(shù)是這樣寫的:
void?funMy(int?a,double*?b,float?other)
這時,可以通過std::bind來實現(xiàn)函數(shù)的綁定。std::placeholders::_1這種占位符就是用在變量綁定的,但是橫看豎看都覺得別扭
上面的例子得這樣寫
double??b?=?1.0; float?other?=?2.0; std::bind(funMy,std::placeholders::_1,&b,other));
當然,如果你不知道還有·std::bind·這樣的函數(shù),你可能會這樣寫:
void?funMy_2(int?a)
{
????double??b?=?1.0;
????float?other?=?2.0;
????funMy(a,&b,other?);
}這樣就把那個三參數(shù)的funMy(int a,double* b,float other)轉(zhuǎn)換為單參數(shù)的fun1(int a),使得函數(shù)指針的參數(shù)一致,但是得再寫一個函數(shù)好麻煩的……
但是有了Lambda表達式后,第二種之前比較不好的方式反而變得更好
因為funMy_2可以這樣代替:
double??b?=?1.0;
float?other?=?2.0;
[&](int?a){funMy(a,&b,other?);}直接就產(chǎn)生一個匿名的void(*(int))函數(shù)指針!





