4

If I have a class (that mimic some of STL's container) like this:


class Elem {
public:
  void prepare(); // do something on *this
  // ...

};

class Selector {
public:
  typedef vector<Elem *> container_type;
  typedef container_type::iterator iterator;

  iterator begin() { return cont_.begin(); }
  iterator end() { return cont_.end(); }

  void check_all();

private:
  prepare_elem(Elem *p); // do something on 'p'
  container_type cont_;

};

If I want to call prepare() for all elements in 'cont_', I could make the following function:


void Selector::check_all() {
  for_each(cont_.begin(), cont_.end(), mem_fun(&Elem::prepare));

}

My question is, what if I want to call Selector::prepare_elem() for all elements in 'cont_'? My initial approach won't compile:


void Selector::check_all() {
  for_each(cont_.begin(), cont_.end(),
           mem_fun(&Selector::prepare_elem));

}

Second approach also failed:


void Selector::check_all() {
  for_each(cont_.begin(), cont_.end(),
           bind1st(mem_fun(&Selector::prepare_elem), this));
}

Is there anyway to use std::for_each() to call Selector::prepare_elem()?

If there's way, I'd like to know a solution without boost.

RedBlueThing
  • 42,006
  • 17
  • 96
  • 122
cinsk
  • 1,576
  • 2
  • 12
  • 14
  • 2
    What are the error messages you're getting? FTR, this question looks like it's addressing a similar issue. http://stackoverflow.com/questions/1762781/mem-fun-and-bind1st-problem – jwismar Oct 18 '10 at 05:56
  • 1
    Hmm, I answered without looking closely enough at your last attempt. That should be valid, see it compile here (errors are from the linker): http://ideone.com/xD5b3 – Potatoswatter Oct 18 '10 at 06:06
  • Did you provide implementation for `prepare_elem` ? Otherewise, there is no issue. – Naveen Oct 18 '10 at 06:11

1 Answers1

1

If you don't want to use boost::bind - use std::tr1::bind.

Abyx
  • 12,345
  • 5
  • 44
  • 76