Topic: Proposal: STL pointer modifier for unary_function's and binary_function's


Author: sean@delta.com (Sean L. Palmer)
Date: 1996/10/01
Raw View
I've noticed standard templates for adapting pointers to unary_function's
and such to act like normal unary_function's, and vice-versa, but I've
found that I have to make many unary_function derivatives which only serve
to take pointers to a class and call a standard unary_function on the
objects they point to.

What I propose is to make a standard set of function adaptors which take a
normal unary_function or binary function and make it work with pointers to
its type instead of object references of its type.

Something like this:

template <class T>
struct unary_fn_ptr : unary_function<const T::value_type*,T::return_type> {
  T::return_type operator ()(const T::value_type* t) {
    return T::operator()(*t);
  }
};

template <class T>
struct binary_fn_ptr : binary_function<const T::left_type*,
                                       const T::right_type*,T::return_type>
{
  T::return_type operator ()(const T::left_type* l,const T::right_type* r)
{
    return T::operator()(*l,*r);
  }
};


I have probably done this wrong as I haven't done that much snooping on
unary_function and binary_function recently, but you get the general idea.
unary_function must provide the types it was templatized on as member
typedefs, which I think it already does but I don't know the names offhand.

They could be just one class with overloaded operator () if the compiler
only instantiated and checked member functions when used (actually called)
instead of when the class is instantiated.

This would allow this kind of thing very easily:

{
  vector<k*> vkp;

  return find_if(vkp.begin(),vkp.end(),binary_fn_ptr<equals<k,k> >());
}

Presently I have to either make a new binary_function class that takes
pointers or provide a global bool operator ==(k*,k*), or make my own
equivalent of these classes.

I think vectors of pointers will be common enough that this is warranted.

Of course the names will need to be better, but I think it would be highly
useful.
---
[ 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
]