很多人反对重新发明轮子,那是站在一个项目的立场上去思考。如果业余时间去学着摸索轮子发明的历程,会比看N多书更有用。 以下是看了 《c++沉思录》后,练习写的函数配接器。 //FuncBinder.h #ifndef _FUNC_BINDER_H_ #define _FUNC_BINDER_H_ template<typename arg1, typename arg2, typename result> struct Binary_Function { // base class for binary functions typedef arg1 First_Argument; typedef arg2 Second_Argument; typedef result Result_Type; }; template<typename T> class Binder1st { typedef typename T::First_Argument Arg1Type; typedef typename T::Second_Argument Arg2Type; typedef typename T::Result_Type ResultType; public: Binder1st(T& fun, Arg1Type& a1t) : m_fun(fun), m_rt(a1t){} ResultType operator()(Arg2Type a2t) { return (m_fun(m_rt, a2t)); } private: T m_fun; Arg1Type m_rt; }; template<typename T> inline Binder1st<T> Bind1st(T& fun, typename T::First_Argument a1t) { return (Binder1st<T>(fun , a1t)); } template<typename T> class Equal : public Binary_Function<T, T, bool> { public: bool operator()(T& t1, T& t2) const { return t1 == t2; } }; #endif 以下是测试代码 #include <iostream> #include <list> #include <algorithm> #include "FuncBinder.h" using namespace std; int main() { list<int> iList; iList.push_back(1); iList.push_back(2); list<int>::iterator iter1(find_if(iList.begin(), iList.end(), Bind1st(Equal<int>(), 1))); return 0; }