Boost logo

Boost :

From: jsiek_at_[hidden]
Date: 2000-01-27 00:08:52


So there's been a bunch of discussion about variations and additions
to the composition library. I don't know if y'all have considered
this before, but a nice interface could be provided for functional
composition by using a simple form of expression templates. This
solves the usability problem of Nico's library. Several have
mentioned that it is difficult to create complex compositions.

Basically, the idea is to overload all the typical operators
(+, -, <, ==) for functor objects, and use Nico's composition
library as the nodes in the expression tree. It's really not
all that hard to do...

Here is a couple snippets of a prototype implementation to give
you an idea:

// define a base class for functions, equiped with the B&N trick
template <class Arg, class Result, class Derived>
struct unary_functor : public std::unary_function<Arg,Result> {
  typedef Arg argument_type;
  typedef Result result_type;
  Derived& down_cast() { return static_cast<Derived&>(*this); }
  const Derived& down_cast() const{ return static_cast<const Derived&>(*this);}
};

// here's an example functor
template <class Tx, class Ty>
struct less_functor
   : public binary_functor<Tx, Ty, bool, less_functor<Tx,Ty> >
{
  bool operator()(Tx x, Ty y) const { return x < y; }
}

// overload the operator< for the unary_functor base class
template <class A1, class R1, class D1, class A2, class R2, class D2>
compose_f_gx_hy_t< less_functor<R1,R2>, D1, D2 >
operator<(const unary_functor<A1,R1,D1>& f1, const unary_functor<A2,R2,D2>& f2)
{
  return compose_f_gx_hy(less_functor<R1,R2>(),
                         f1.down_cast(),
                         f2.down_cast());
}

// Now here's a peice of one of the previous examples, but now
// using the expression templates

  sort(aPersonVec.begin(), aPersonVec.end(),
       mem_functor(&Person::GetName)
       < mem_functor(&Person::GetName));

// (mem_functor is like mem_fun, but derives from unary_functor instead)

Cheers,

Jeremy


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk