views:

81

answers:

3

Hello, here's today's dilemma:

suppose I've

class A{
  public:
   virtual void doit() = 0;
}

then various subclasses of A, all implementing their good doit method. Now suppose I want to write a function that takes two iterators (one at the beginning of a sequence, the other at the end). The sequence is a sequence of A subclasses like say list<A*> or vector... The function should call all the doit methods while scanning the iterators... How to do this? I've thought of:

template<typename Iterator> void doList(Iterator &begin, Iterator &end) {
    for (; begin != end; begin++) {
     A *elem = (serializable*) *begin;
     elem.doIt();
    }
}

but gives weird errors... do you have better ideas or specific information? Is it possible to use list<A> instead of list<A*>?

+1  A: 

You should provide error messages to get better answers.

In your code, the first thing that comes to mind is to use

elem->doIt();

What is the "serializable" type ?

Benoît
sorry serializable stands for A. How can the compiler know that elem has a doIt method???
gotch4
Because it knows that elem is of type A*
anon
+4  A: 

Why do you think you need the cast? If it is a collection of A * you should just be able to say:

(*begin)->doIt();
anon
+4  A: 

You can use the std::foreach for that:

std::for_each( v.begin(), v.end(), std::mem_fun( &A::doIt ) );

The std::mem_fun will create an object that calls the given member function for it's operator() argument. The for_each will call this object for every element within v.begin() and v.end().

xtofl
+1: but `foreach` should be spelled `for_each`
David Rodríguez - dribeas
why - thanks! I looked just a little too much at PHP code...
xtofl