Topic: pointers to member functions and templates (mem_fun adaptor)


Author: jbuck@Synopsys.COM (Joe Buck)
Date: 1996/06/07
Raw View
Suppose that in a template we are given a pointer to member function
as an argument and we infer both the object type and result type from
it, for example

template<class Object, class Result>
class apply_pmf_pointer : public unary_function<Object*,Result>
{
 public:
    apply_pmf_pointer(Result (Object::*m)())
 : member(m) {}
    Result operator()(Object* object) { return (object->*member)();}
 private:
    Result (Object::*member)();
};

template<class Object, class Result>
inline apply_pmf_pointer<Object,Result> mem_fun(Result(Object::*m)())
{
    return apply_pmf_pointer<Object,Result>(m);
}

which I understand is similar to a proposal by Stroustrup that was
accepted as an addition to STL.  Here the second template gets both
the Object and the Result argument from the single argument to mem_fun.

Now, what happens when we supply a const member function, e.g.
&string::length ?  One possibility is to reject this case as a mismatch,
but it would be really nice if in that case mem_fun would instantiate
apply_pmf_pointer<const string, size_t>.  Conversely, what is the
meaning of apply_pmf_pointer<const string, size_t>?  It seems that
if
 Result (const Object::*m)()

is equivalent to

 Result (Object::*m)() const

this comes out cleanly.  If not, then it seems Stroustrup's proposal
would need to add additional adaptors to handle const member functions.

I found this when I was playing with (my interpretation of) Stroustrup's
adaptor proposal.  e.g. to print out the lengths of the strings in a
vector of strings:

 vector<string> svec;
 ostream_iterator o_iter(cout, "\n");
 ... fill up svec ...
 transform(svec.begin(), svec.end(), mem_fun_ref(&string::length),
    o_iter);


--
-- Joe Buck  <jbuck@synopsys.com> (not speaking for Synopsys, Inc)

Work for something because it is good,
not just because it stands a chance to succeed.    -- Vaclav Havel
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]