vector<Book> books;
void CBookEditDlg::ForEachBookFunctor(Book book)
{
??? ......
}
for_each(books.begin(), books.end(), std::bind1st(mem_fun(&CBookEditDlg::ForEachBookFunctor), this));
關(guān)鍵點(diǎn)在于mem_fun和bind1st的使用。
for_each的實(shí)現(xiàn)中最核心的一個(gè)調(diào)用:functor(*iterater);
由于類非靜態(tài)成員函數(shù),必須在實(shí)例上調(diào)用:(instance->*pfn)(params);
所以for_each無法直接使用傳過去的函數(shù)地址,函數(shù)指針的第一個(gè)參數(shù)是類的一個(gè)實(shí)例指針(this指針),所以必須想辦法把這個(gè)指針傳過去(使用std::bind1st)
關(guān)于mem_fun的一些資料,請(qǐng)參考
http://www.stlchina.org/documents/EffectiveSTL/files/item_41.html對(duì)于帶兩個(gè)以上參數(shù)的成員函數(shù),用stl是不能達(dá)到目的的,因?yàn)閙em_fun只能生成不帶參數(shù),或者是僅帶一個(gè)參數(shù)的函數(shù)對(duì)象(functor),bind1st和bind2st也只能對(duì)第一個(gè)或者是第二個(gè)參數(shù)進(jìn)行綁定。
要實(shí)現(xiàn)對(duì)任意數(shù)量參數(shù)的成員函數(shù)生成functor,必須對(duì)stl進(jìn)行擴(kuò)展,所幸boost已經(jīng)做到了這點(diǎn),boost::bind和boost::mem_fn就是更加泛化的std::bind1st和std::mem_func
??? void ForEachClassFunctor(Class c, CTreeItem treeItem)
??? {
??? ??? treeView.InsertItem(c.name.c_str(), treeItem, NULL);
??? }
??? void ForEachBookFunctor(Book book)
?? ?{
?? ??? ?CTreeItem treeItem = treeView.InsertItem(book.name.c_str(), NULL, NULL);
?? ??? ?vector<Class> v;
?? ??? ?v.push_back(Class(0,0,"nameClass1", "titleClass1"));
?? ??? ?for_each(v.begin(), v.end(),
??????????? boost::bind(boost::mem_fn(&CBookEditDlg::ForEachClassFunctor), this, _1, treeItem));
?? ?}