[C++-sig] Re: iterators and abstact base class

Francois Ostiguy ostiguy at fnal.gov
Wed Mar 10 17:10:08 CET 2004


On Tue, 9 Mar 2004, David Abrahams wrote:

> > Hi -
> >
> > This has to be an FAQ. I searched the list archives and I was not able
> > locate a satisfactory solution to the following problem:
> >
> > Assume an abstract base class A and a derived class B. I have an iterator
> > I for a container C holding B-type objects.  The iterator returns a
> > pointer to the base class A.
> > At runtime, I.next()
>
> ?? This is a standard C++ iterator, or something else??
>
> > returns a type A which cannot be instantiated.
>
> Clearly it can't return A; it can return a reference to A, though.
>
> > I would like to iterate through my container and call a (virtual) function
> > on each element.  Can you point me to an idiom/technique that would
> > allow me to accomplish this ?
>
> Is this a Python/C++ question, a straight C++ question, or something
> else?  Too many details are missing.
>


Sorry for not being specific enough. This is really a boost.python
question. The iterator is a custom iterator (the code was written
in the early 1990s) which returns a pointer to the base class.
Of course, the object returned is always an instance of a derived class.
So if class C is my container class and next is the "iterator"

class A;              // abstract class
class B: public A {
...
};

C c;                 // container class, contains objects instances of
                     // classes derived from A
...

Iterator i(c);

A* a = i. next();     //  generic way to retrieve the next element in the
                          container
a.function();         //  calls a virtual function on the element


I want to achieve in python

b1 = B(..)    # appropriate contructor
b2 = B(..)    #
c = C(b1, b2) # constructs a C which contains b1 and b2
i = I(c)      # i is an iterator for c

a = i.next()  <<<<==== this is the problem. i.next() must return something
                       that can be held into python object a. In C++
                       i.next() returns a type A*.

a.function()

...

How do I define a python type that can be used to hold what i.next() returns ?

As always, your help is greatly appreciated.

-Francois

----------------------------------------------------------------------------
Dr. Jean-Francois OSTIGUY                              voice: (630) 840-2231
Beam Physics Dept MS220                                  FAX: (630) 840-6039
Fermi National Accelerator Laboratory                email: ostiguy at fnal.gov
Batavia IL 60510-0500                           WWW:www-ap.fnal.gov/~ostiguy





More information about the Cplusplus-sig mailing list