Skip to content

Instantly share code, notes, and snippets.

@emdeesee
Last active December 26, 2015 06:29
Show Gist options
  • Save emdeesee/7108675 to your computer and use it in GitHub Desktop.
Save emdeesee/7108675 to your computer and use it in GitHub Desktop.
Simple use of pointers to member functions
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct O
{
void m(int n) const
{
cout << n << "\n";
}
void minus_one(int n) const
{
cout << n-1 << "\n";
}
};
// This function takes an object of type O and a pointer to
// one of its methods, and calls the method on the object.
void f(const O &o, void (O::*action)(int) const, int n)
{
// Maybe do a bunch of stuff...
(o .* action)(n);
// More stuff...
}
int main()
{
O o;
// Cause 0 to be printed by binding m to o with the .* ("dot star") operator.
(o .* &O::m)(0);
// Cause 1 to be printed by using mem_fun to create and object that calls O::m
// (via its pointer) using an object of type O and an argument.
mem_fun(&O::m)(&o, 1);
// Cause 42 to be printed 16 times using the for_each algorithm, and O::m bound
// to o.
vector<int> c(16, 42);
for_each(c.begin(), c.end(), bind1st(mem_fun(&O::m), &o));
// Call o's method m to print 100.
// This is equivalent to o.m(100), except that in practice,
// f will be doing more than just calling the method on the
// object.
f(o, &O::m, 100);
// Call o's method minus_one to print 99.
// This is equivalent to o.minus_one(100), with the same caveats
// as above.
f(o, &O::minus_one, 100);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment