/* * mem_fun_ref-test.cc * * Shows how helper function mem_fun is used to adapt pointers to member * functions. mem_fun can adapt to member functions with one or no argument. * The two main purposes are to create function objects making it possible to * call member functions with the same syntax as an ordinary function call, * i.e. f(args), and also obtain the typdefs inherited from unary_function and * binary_function, which some component require (not algorithm for_each * though). The function objects that mem_fun_ref creates are for the case * when the objects for which member functions are to be called are NOT * referenced by pointers, e.g. if we have a vector storing some kind of class * type objects. What 'ref' in the name mem_fun_ref is referring to is that * operator() in the created function object takes the class object by reference. */ #include #include #include #include #include using namespace std; class X { public: X(const int i) : value_(i) {} int times(const int n) const { return n * value_; } operator int() const { return value_; } private: int value_; }; int main() { int a [] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; vector v(a, a + 10); // Type conversion operator int() is used when writing X objects // to the output stream. cout << "v: "; copy(v.begin(), v.end(), ostream_iterator(cout, " ")); cout << endl; cout << "a: "; copy(a, a + 10, ostream_iterator(cout, " ")); cout << endl << endl; // transform: // First input range is given by v.begin(), v.end(). // Start of second input range is given by a. // Result is written to cout, using ostream_iterator. // The binary operation applied to each pair from first and second // input range is X::times. // Helper function mem_fun_ref creates a function object bound to X::times // where operator() is declared 'int operator()(X& p, int i)' and makes // the call 'return p.times(i)'. cout << "v*a: "; transform(v.begin(), v.end(), a, ostream_iterator(cout, " "), mem_fun_ref(&X::times)); cout << endl; return 0; }