Re: [Boost-users] [bind] Need Help - Function Composition

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); } Thanks again. B/Rgds Max Hello Watanabe, Your code works well. And it's much more generic and elegant than the original version. Thank you so much! Best regards Max ------------------------------------------------------------------- 新浪空间——与朋友开心分享网络新生活!(http://space.sina.com.cn/ )

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
participants (2)
-
loadcom
-
Steven Watanabe