Boost logo

Boost :

From: Torbjörn Gyllebring (torbjorn.gyllebring_at_[hidden])
Date: 2003-05-29 19:46:07

Im new to the list but I got an idea I want to share, maybe this is old and
well known
but for me it's new and solves a very real problem.

While using STL i often end up writing code like:
for( containertype::iterator itr = cont.begin(); itr != cont.end(); ++itr)
  object->doThing( *itr);

where object some times is an aggregate object and sometimes is well "this".

anyway, STL have a good way of handling member functions and function
mem_fun, mem_fun_ref, ptr_fun, they are all very usefull in translating from
one function call form to the func( obj); form required by std::algorithms
but they simply
doesn't help in my situation, so what I did was I invented obj_fun that
simply put transforms
class_instance->function( obj); to the required func( obj); it's a simple
concept and I
haven't seen it used before so feel free to correct me if this is actually
well known.

code will follow:

template <typename R, typename C, typename F, typename A>
class obj_fun_t
C *m_pObj;
F m_pFun;
 typedef R return_type;
 typedef A argument_type;

 obj_fun_t(C* pC, F pFun): m_pObj( pC), m_pFun( pFun){}
 R operator()(A arg){ return (m_pObj->*m_pFun)( arg);}

template <typename R, typename C, typename A>
obj_fun_t<R, C, R (C::*)(A), A> obj_fun(C *pC, R (C::*pFun)(A))
{ return obj_fun_t<R, C, R (C::*)(A), A>( pC, pFun);}

template <typename R, typename C, typename A>
obj_fun_t<R, const C, R (C::*)(A) const, A> obj_fun(const C *pC, R
(C::*pFun)(A) const)
{ return obj_fun_t<R, const C, R (C::*)(A) const, A>( pC, pFun);}

that's the basics the second obj_fun overload is needed to make it work with
const member
functions, a usage example would be:

struct B
int f(int i){ cout << i << "\t";}
int g(int i) const { cout << i << "\n";}

int main(int argc, char *argv[])
  vector<int> ivec;
 for(int i = 0; i < 10; ++i)
  ivec.push_back( i);
 B b;
 for_each( ivec.begin(), ivec.end(), obj_fun( &b, &B::f));
 cout << endl;
 for_each( ivec.begin(), ivec.end(), obj_fun( &b, &B::g));
 return 0;

if something like this is already in boost (a friend who uses it claims it's
not) then im
really sorry for wasting your time, else maybe this would be a candidate for

best wishes
Torbjörn Gyllebring

Boost list run by bdawes at, gregod at, cpdaniel at, john at