Reputation: 13259
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*>
?
Upvotes: 0
Views: 256
Reputation: 41509
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()
.
Upvotes: 4
Reputation:
Why do you think you need the cast? If it is a collection of A * you should just be able to say:
(*begin)->doIt();
Upvotes: 4
Reputation: 16994
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 ?
Upvotes: 1