Boost logo

Boost Users :

Subject: Re: [Boost-users] [bind] Need Help - Function Composition
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2008-12-20 13:39:38


AMDG

loadcom wrote:
> One step further, will the following version save one copy construction
> in make_less_by_func()?
>
> template <typename F> struct less_by_func
> {
> typedef bool result_type;
>
> const F & func_;
> less_by_func(const F & func) : func_(func) {}
>
> template<typename T>
> bool operator()(const T& lhs, const T& rhs) const
> { return func_(lhs) < func_(rhs); }
> };
>
> // helper function
> template<typename F> less_by_func<F> make_less_by_func(const F& func)
> { return less_by_func<F>(func); }
>

I don't advise this in general because it requires the argument of
make_less_by_func to survive for a while.

boost::function<bool(int, int)> f = make_less_by_func(boost::bind(...));

f(1, 2); // undefined behavior because of the dangling reference.

If you really want this capability

#include <boost/ref.hpp>

template <typename F> struct less_by_func
{
    typedef bool result_type;
    F func_;
    less_by_func(const F & func) : func_(func) {}

    template<typename T>
    bool operator()(const T& lhs, const T& rhs) const
    { return boost::unwrap_ref(func_)(lhs) <
             boost::unwrap_ref(func_)(rhs); }
};

which allows

make_less_by_func(boost::cref(boost::bind(...)))

In Christ,
Steven Watanabe


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net