vector<Book> books;
void CBookEditDlg::ForEachBookFunctor(Book book)
{
??? ......
}
for_each(books.begin(), books.end(), std::bind1st(mem_fun(&CBookEditDlg::ForEachBookFunctor), this));
關鍵點在于mem_fun和bind1st的使用。
for_each的實現(xiàn)中最核心的一個調用:functor(*iterater);
由于類非靜態(tài)成員函數(shù),必須在實例上調用:(instance->*pfn)(params);
所以for_each無法直接使用傳過去的函數(shù)地址,函數(shù)指針的第一個參數(shù)是類的一個實例指針(this指針),所以必須想辦法把這個指針傳過去(使用std::bind1st)
關于mem_fun的一些資料,請參考
http://www.stlchina.org/documents/EffectiveSTL/files/item_41.html對于帶兩個以上參數(shù)的成員函數(shù),用stl是不能達到目的的,因為mem_fun只能生成不帶參數(shù),或者是僅帶一個參數(shù)的函數(shù)對象(functor),bind1st和bind2st也只能對第一個或者是第二個參數(shù)進行綁定。
要實現(xiàn)對任意數(shù)量參數(shù)的成員函數(shù)生成functor,必須對stl進行擴展,所幸boost已經做到了這點,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));
?? ?}