简体   繁体   中英

c++ templated container scanner

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*> ?

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

(*begin)->doIt();

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() .

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM