#ifndef ZMMEMBERFUNCTION_H #define ZMMEMBERFUNCTION_H // ---------------------------------------------------------------------- // // ZMmemberFunction.h - utility templates & macro to treat (obj,mbrFctn) // pairs as functors (objects having a function-call operator) // // Usage: // The object resulting from the call ZMmemberFunction(obj,mbrFctnName) // may be used in the place of any niladic function, assuming the // named mbrFctn is itself niladic (having no arguments); this is // particularly useful when passed to a function expecting a niladic // function as a parameter // // In the following examples, assume myObj is a instance of a class C // that has a member function itsFctn() normally called via // myObj.itsFctn() // // Example 1: construct and call right away (silly): // cout << ZMmemberFunction( myObj, itsFctn )() << endl; // // Example 2: construct and pass to f (for probable invocation in f): // f( ZMmemberFunction( myObj, itsFctn ) ); // // History: // 28-Aug-1997 Walter Brown Initial draft, patterned after examples // found in Stroustrup: The C++ Programming Language (3rd edition) // 02-Sep-1997 Walter Brown Renamed functions & objects, and // polished for production use // // ---------------------------------------------------------------------- #include // ---------------------------------------------------------------------- // ZMmbrFctn_<> functor class to package an object together with a // niladic member function of its class, enabling the pair to be treated // as if they constituted an ordinary niladic function: template< typename Obj, typename Res > class ZMmbrFctn_ : public binary_function< Obj &, Res (Obj::*)(), Res > { public: explicit ZMmbrFctn_( // constructor const first_argument_type o , const second_argument_type f ) : o_(o) , f_(f) { } result_type operator() () { // fctn-call (invocation) operator return (o_ .* f_) (); } protected: first_argument_type o_; // object of interest second_argument_type f_; // mbr fctn (of o_) to be invoked }; // ZMmbrFctn_<> // ---------------------------------------------------------------------- // auxiliary ZMmemberFunction_<> function to construct a ZMmbrFctn<> // object (and, not incidentally, to determine implicitly the classes // involved!): template< typename Obj, typename Res > ZMmbrFctn_< Obj, Res > ZMmemberFunction_( Obj & o , Res (Obj::*f)() ) { // call class' constructor & return resulting functor return ZMmbrFctn_< Obj, Res >( o, f ); } // ZMmemberFunction_() // ---------------------------------------------------------------------- // ZMmemberFunction, public interface macro: #define ZMmemberFunction( o, f ) ZMmemberFunction_( (o), (o).f ) #endif // ZMMEMBERFUNCTION_H