#ifndef WORLD_H #define WORLD_H #include "base.h" //! a collection of pointers to /whatof/ template <class whatof> class World : public common { private: whatof **planet; int array_size, used_size; friend class iterator; public: class iterator { World *w; int i; friend class World; iterator(World *w, int i) : w(w), i(i) { } public: bool operator==(const iterator &other) const { if (w != other.w) abort(); return i == other.i; } void operator++(int=0) { i++; } void operator--(int=0) { i--; } operator whatof*() { return (i<w->used_size && i>=0)?w->get(i):0; } whatof *operator->() { return operator whatof*(); } }; iterator begin() { return iterator(this, 0); } iterator end() { return iterator(this, getsize()); } //! construct an empty world World(); //! copy constructor World(const World &a); virtual ~World(); void operator=(const World &a); //! add given object void add(whatof *what) { if (what) add(*what); } //! remove given object void remove(const whatof *what) { if (what) remove(*what); } void add(whatof &what); void remove(const whatof &what); //! get object here with id /tag/ whatof *rawget(const char *tag) const; //! get object here with id /tag/ virtual whatof *get(const char *tag) const; whatof *get(const string &s) const { return get(s.c_str()); } //! number of elements int getsize() const; //! get nth element whatof *get_nth(int i) const; whatof *get(int i) const; //! is /o/ int this? bool contains(whatof *o) const; //! is this not empty? operator bool() const { return getsize()!=0; } //! union and assignment void operator += (const World<whatof> &w) { int limit = w.getsize(); for (int i=0;i<limit;i++) { add(w.get(i)); } } //! union World<whatof> operator +(const World<whatof> &w) const { World<whatof> w2 = *this; w2 += w; return w2; } //! difference and assignment void operator -= (const World<whatof> &w) { int limit = w.getsize(); for (int i=0;i<limit;i++) { remove(w.get(i)); } } //! difference World<whatof> operator -(const World<whatof> &w) const { World<whatof> w2 = *this; w2 -= w; return w2; } // intersection and assignment void operator *=(const World<whatof> &w) { int limit = getsize(); for (int i=0;i<limit;i++) { if (!w.contains(get(i))) { remove(get(i)); i--; continue; } } } //! intersection World<whatof> operator *(const World<whatof> &w) const { World<whatof> w2 = *this; w2 *= w; return w2; } }; //! iterate over a world #define foreach(planet,what,__i) if ((planet)->getsize()||(__i=0)) for (__i=0, \ what=(planet)->get_nth(__i) ; (__i)<((planet)->getsize()); \ __i++, what=(planet)->get_nth(__i) ) //! iterate over a world in alphabetical order #define foreach_alpha(planet,what,__i) if ((planet)->getsize()||(__i=0)) for (__i=0, \ what=(planet)->get_nth((planet)->getsize()-__i-1) ; (__i)<((planet)->getsize()); \ __i++, what=(planet)->get_nth((planet)->getsize()-__i-1) ) #define iforeach(a, b) for (typeof((b).begin()) a=(b).begin();a != (b).end();a++) #define auto(a, b) typeof(b) a = b #endif