/* * mem_fun-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 creates are for the case when * the objects for which member functions are to be called are referenced by * pointers, e.g. if we have a vector storing pointers to some kind of class * type objects. operator() in the created function object will bind the class * object by a pointer parameter. */ #include #include #include #include #include using namespace std; class X { public: X(const int i = 0) : value_(i) {} int times(const int n) const { return n * value_; } operator int() const { return value_; } private: int value_; }; void print(X* px) { cout << *px << ' '; // uses type conversion X::operator int() } int main() { vector v; for (int i = 1; i <= 10; ++i) v.push_back(new X(i)); int a[] = { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }; cout << "v: "; for_each(v.begin(), v.end(), print); // or: ptr_fun(print) 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 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(&X::times)); cout << endl; return 0; }