1: /*
   2:  *
   3:  *  mftest.cc
   4:  *  by Jeffrey D. Wheelhouse (jdw@wheelhouse.org)
   5:  *  Version 1.0
   6:  *  11/19/2002
   7:  *
   8:  *  far_mem_fun sample implementation.
   9:  *
  10:  *  This software is in the public domain.
  11:  *
  12:  */
  13: 
  14: 
  15: /**********************
  16: *                     *
  17: *  LANGUAGE INCLUDES  *
  18: *                     *
  19: **********************/
  20: 
  21: 
  22: #include <functional> 
  23: #include <iostream> 
  24: #include <vector> 
  25: 
  26: 
  27: /***************
  28: *              *
  29: *  REFERENCES  *
  30: *              *
  31: ***************/
  32: 
  33: 
  34: using std::cout;
  35: using std::endl;
  36: using std::for_each;
  37: using std::unary_function;
  38: using std::vector;
  39: 
  40: 
  41: /**********************
  42: *                     *
  43: *  CLASS ACCUMULATOR  *
  44: *                     *
  45: **********************/
  46: 
  47: 
  48: template <class Type> class basic_accumulator {
  49: public:
  50:   basic_accumulator(void) { m_typ = 0; };
  51:   bool accumulate(Type i_typ) { m_typ += i_typ; };
  52:   Type results(void) { return m_typ; };
  53: protected:
  54:   Type m_typ;
  55: };
  56: typedef basic_accumulator<int> accumulator;
  57: 
  58: 
  59: /*********************************
  60: *                                *
  61: *  TEMPLATE CLASS FAR_MEM_FUN_T  *
  62: *                                *
  63: *********************************/
  64: 
  65: 
  66: template <class Result, class Type, class Param> 
  67: class far_mem_fun_t : public unary_function<Param,Result> {
  68: public:
  69:   explicit far_mem_fun_t(Type &ir_typ, Result (Type::*i_pmf)(Param)) {
  70:     m_ptyp = &ir_typ;
  71:     m_pmf = i_pmf;
  72:   };
  73:   Result operator()(Param i_prm) { return (m_ptyp->*(m_pmf))(i_prm); };
  74: 
  75: protected:
  76:   Type *m_ptyp;
  77:   Result (Type::*m_pmf)(Param);
  78: };
  79: 
  80: 
  81: /**********************************
  82: *                                 *
  83: *  TEMPLATE FUNCTION FAR_MEM_FUN  *
  84: *                                 *
  85: **********************************/
  86: 
  87: 
  88: template <class Result, class Type, class Param>
  89: far_mem_fun_t<Result,Type,Param> far_mem_fun(Type &ir_typ, Result (Type::*i_pmf)
  90: (Param) ) {
  91:   return far_mem_fun_t<Result,Type,Param>(ir_typ,i_pmf);
  92: }
  93: 
  94: 
  95: /******************
  96: *                 *
  97: *  FUNCTION MAIN  *
  98: *                 *
  99: ******************/
 100: 
 101: 
 102: int main() { 
 103:   accumulator a;
 104:   vector<int> v;
 105: 
 106:   v.push_back(1);
 107:   v.push_back(1);
 108:   v.push_back(2);
 109:   v.push_back(3);
 110:   v.push_back(5);
 111:   v.push_back(8); 
 112: 
 113:   for_each(v.begin(),v.end(),far_mem_fun(a,&accumulator::accumulate));
 114: 
 115:   cout << a.results() << endl;
 116: 
 117:   return 0;
 118: }
 119: 
 120: 
 121: