/* * * mftest.cc * by Jeffrey D. Wheelhouse (jdw@wheelhouse.org) * Version 1.0 * 11/19/2002 * * far_mem_fun sample implementation. * * This software is in the public domain. * */ /********************** * * * LANGUAGE INCLUDES * * * **********************/ #include #include #include /*************** * * * REFERENCES * * * ***************/ using std::cout; using std::endl; using std::for_each; using std::unary_function; using std::vector; /********************** * * * CLASS ACCUMULATOR * * * **********************/ template class basic_accumulator { public: basic_accumulator(void) { m_typ = 0; }; bool accumulate(Type i_typ) { m_typ += i_typ; }; Type results(void) { return m_typ; }; protected: Type m_typ; }; typedef basic_accumulator accumulator; /********************************* * * * TEMPLATE CLASS FAR_MEM_FUN_T * * * *********************************/ template class far_mem_fun_t : public unary_function { public: explicit far_mem_fun_t(Type &ir_typ, Result (Type::*i_pmf)(Param)) { m_ptyp = &ir_typ; m_pmf = i_pmf; }; Result operator()(Param i_prm) { return (m_ptyp->*(m_pmf))(i_prm); }; protected: Type *m_ptyp; Result (Type::*m_pmf)(Param); }; /********************************** * * * TEMPLATE FUNCTION FAR_MEM_FUN * * * **********************************/ template far_mem_fun_t far_mem_fun(Type &ir_typ, Result (Type::*i_pmf) (Param) ) { return far_mem_fun_t(ir_typ,i_pmf); } /****************** * * * FUNCTION MAIN * * * ******************/ int main() { accumulator a; vector v; v.push_back(1); v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(5); v.push_back(8); for_each(v.begin(),v.end(),far_mem_fun(a,&accumulator::accumulate)); cout << a.results() << endl; return 0; }