G
Grey Plastic
I have a program where several classes each have a single static
std::map to keep track of all the instances of that class. For each
of these classes, I want a static lookupByID(int id) method which
returns a pointer to the instance that the id references... e.g...
Item * Item::lookupByID(Uint32 id);
Level * Level::lookupByID(Uint32 id);
Lifeform * Lifeform::lookupByID(Uint32 id);
.... etc. Instead of rewriting the same code for each of these
classes, I instead wrote an Indexable class...
template <class Child> class Indexable {
private:
static std::map<Uint32,Child*> mapByID;
static Uint32 _nextID;
Uint32 _id;
public:
static Child * lookupByID(Uint32 id) { return mapByID[id]; }
Indexable() { _id=_nextID++; mapByID[_id]=(Child*)this; }
~Indexable() { mapByID[_id]=NULL; }
Uint32 id() const { return _id; }
};
and made each of my other classes subclass Indexable...
class Item : public Indexable<Item> { ... };
class Level : public Indexable<Level> { ... };
class Lifeform : public Indexable<Lifeform> { ... };
This achieves what I've wanted, but it still seems a bit weird to me.
How would you guys handle this situation?
std::map to keep track of all the instances of that class. For each
of these classes, I want a static lookupByID(int id) method which
returns a pointer to the instance that the id references... e.g...
Item * Item::lookupByID(Uint32 id);
Level * Level::lookupByID(Uint32 id);
Lifeform * Lifeform::lookupByID(Uint32 id);
.... etc. Instead of rewriting the same code for each of these
classes, I instead wrote an Indexable class...
template <class Child> class Indexable {
private:
static std::map<Uint32,Child*> mapByID;
static Uint32 _nextID;
Uint32 _id;
public:
static Child * lookupByID(Uint32 id) { return mapByID[id]; }
Indexable() { _id=_nextID++; mapByID[_id]=(Child*)this; }
~Indexable() { mapByID[_id]=NULL; }
Uint32 id() const { return _id; }
};
and made each of my other classes subclass Indexable...
class Item : public Indexable<Item> { ... };
class Level : public Indexable<Level> { ... };
class Lifeform : public Indexable<Lifeform> { ... };
This achieves what I've wanted, but it still seems a bit weird to me.
How would you guys handle this situation?