c++ - an iterator for an abstract class -


i have abstract class, example class represents geometrical shape. have concrete classes inheriting shape, such rectangle , triangle.

i iterate on points (another class) shape composed of, shape must supply interface it. iteration should in manner:

for(point p : shapeobject){ ... code} 

but don't want shape class determine child class containers use. example, rectangle have std::array<point, 4> container while triangle have std::array<point, 3> container.

so question here is, elegant c++ way this?

a simple way solve "problem"* in particular case points stored in containers supporting random access iteration (such std::array or std::vector use plain pointers iterators:

struct point {};  struct shape {     typedef point* iterator;     typedef const point* const_iterator;     virtual iterator begin() = 0;     virtual const_iterator begin() const = 0;     virtual iterator end() = 0;     virtual const_iterator end() const = 0;     virtual ~shape() {} }; 

and have derived classes implement begin(), end() using pointers first , past end elements of array hold.

alternatively, use type-erasure e.g. boost.any_range or via any_iterator type. may beyond scope of answer here article on precisely problem.


* assuming there problem requires hiding type of iterators. note can write template code deal different iterator types.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -