Boost logo

Boost Users :

From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2007-03-12 08:51:16


Hi!

the std::find_if function takes as it's third parameter an unary predicate function or function
object which evaluates the condition.

To implement this you can write your comparison function looking like:

template<class FunctionType>
struct compare_functions
{
  compare_functions(FunctionType f) : func_(f)
  {}

  template<class RefObj>
  bool operator()(RefObj r)const
  {
     return func_==r; //boost::reference_wrapper<T> has an operator T& which is called implicitly
  }

private:
    FunctionType func_;
};

modifications in your code:
void remove(boost::function<void (int v)> fun)
{
    std::list<boost::function<void (int v)> >::iterator iter;

    //IMPLEMENTATION
    std::find_if(fun_list.begin(), fun_list.end(), compare_functions(fun));

    if(iter != fun_list.end())
      fun_list.erase(iter);
}

You could also skip the compare_functions implementation and use boost::lambda and placeholder
library to write you code like this:
    std::find_if(fun_list.begin(), fun_list.end(), _1==fun);

With Kind Regards,

Ovanes Markarian

On Mon, March 12, 2007 09:48, misiu wrote:
> Hello,
>
> Could you please tell me how to compare two boost::function objects
> packet with boost::ref. I have container which has boost::function
> elements and to add elements is not a problem but to remove particular
> one I don't know how to do that (compare two boost:ref-s). The problem
> is shown in the code below.
>
> Regards,
> Bartek
>
>
> //code
>
> #include <iostream>
> #include <list>
> #include <boost/ref.hpp>
> #include <boost/function.hpp>
>
> struct test{
> int a;
> void operator() (int aa)
> { a += aa; }
> };
>
> struct function_list {
> std::list<boost::function<void (int v)> > fun_list;
>
> void add(boost::function<void (int v)> fun)
> {
> fun_list.push_back(fun);
> }
>
> void remove(boost::function<void (int v)> fun)
> {
> std::list<boost::function<void (int v)> >::iterator iter;
>
> //HOW TO IMPLEMETN THIS FIND_IF?
> //std::find_if(fun_list.begin(), fun_list.end(), MISSING_PART);
>
> if(iter != fun_list.end())
> fun_list.erase(iter);
> }
> };
>
> int main(int argc, char **argv) {
>
> test a, b;
> function_list f;
>
> f.add(boost::ref(a));
> f.add(boost::ref(b));
> //DOES NOT WORK
> f.remove(boost::ref(a));
> }
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


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