http://www.cnblogs.com/shootingstars/archive/2008/11/14/860042.html
以前使用bind1st以及bind2nd很少,后來發現這兩個函數還挺好玩的,于是關心上了。
在C++ Primer對于bind函數的描述如下:
“
綁定器binder通過把二元函數對象的一個實參綁定到一個特殊的值上將其轉換成一元函數對象
C++標準庫提供了兩種預定義的binder 適配器bind1st 和bind2nd 正如你所預料的bind1st 把值綁定到二元函數對象的第一個實參上bind2nd 把值綁定在第二個實參上
例如
為了計數容器中所有小于或等于10 的元素的個數我們可以這樣向count_if()傳遞
count_if( vec.begin(), vec.end(), bind2nd( less_equal<int>(), 10 ));
”
哦,這倒是挺有意思的。于是依葫蘆畫瓢:
{
????std::cout<<i?<<"---"<<j?<<std::endl;?
????returni>j;
}
intmain(intargc,?char*argv[])
{
????(std::bind1st(print,?2))(1);
????return0;
}
滿懷希望它能夠打印
2---1
只不過。。。編譯出錯:
1??? Error??? error C2784: 'std::binder1st<_Fn2> std::bind1st(const _Fn2 &,const _Ty &)' : could not deduce template argument for 'overloaded function type' from 'overloaded function type'????
---不能夠推斷出模板參數for 'overloaded function type' from 'overloaded function type' 。。。。
(還真看不明白。。。)
于是直接看bind1st代碼:
????class_Ty>inline
????binder1st<_Fn2>bind1st(const_Fn2&_Func,?const_Ty&_Left)
????????{????
????????typename?_Fn2::first_argument_type?_Val(_Left);
????????return(std::binder1st<_Fn2>(_Func,?_Val));
????????}
嗯。。。在代碼里
typename?_Fn2::first_argument_type?_Val(_Left)
說必須定義first_argument_type類型,可是我一個函數,哪里來的這個類型定義?嗯,STL一定提供了某種東東用來自動定義這個類型。找啊找,于是找到了ptr_fun。
這個函數自動將一個函數指針轉換為一個binary_function的繼承類pointer_to_binary_function,而在binary_function中定義了first_argument_type。
于是修改代碼:
{
????(std::bind1st(std::ptr_fun(print),?2))(1);
????return0;
}
打印結果如下:
2---1