jjleto said:
I have just learn about "pointer to member". Does someone have an actual
example where "pointers to member" are usefull or necessary ? Can't
always &(myClass.member) be used ?
Assume you have a container of pairs, e.g.
typedef std::vector<std:
air<int, int> > Container;
.... and you want to print all 'first' elements on a row followed by
all 'second' elements on a row. You *can* code functions for printing
the first and second elements, e.g.:
| void printFirst(Container const& c) {
| for (Container::const_iterator it = c.begin(), end = c.end();
| it != end; ++it)
| std::cout << it->first << " ";
| std::cout << "\n";
| }
.... and likewise for 'printSecond()'. However, it would be easier to
have a common function which select the member to be printed using a
pointer to member:
| void print(Container const& c, int std:
air<int, int>::*mem) {
| for (Container::const_iterator it = c.begin(), end = c.end();
| it = end; ++it)
| std::cout << (*it).*mem << " ";
| std::cout << "\n";
| }
Actually, this function is still quite trivial and you might be happy
typing it twice: I'm not, especially as I suspect that I might want
to apply changes in the future (e.g. avoid the dangling space or change
the formatting) which I would have to do multiple time. Thus, I prefer
the additional parameter. Of course, things like this should probably
use an appropriate algorithm which in turn probably needs an
appropriate
functor but this one will use the pointer to member.
Another nice thing about pointer to member is that you the access rules
are not checked for the pointer. That is, although neither some
algorithm
nor some functor can access a private member directly, I can create the
pointer to member from a member function and hand it off to some
functor.