I’m trying to write a function for a database class that is basically just a wrapper around a hash_map of objects (say shapes) indexed by ID numbers that will look up an ID and cast it to the appropriate pointer type.
e.g. I’d like to be able to do something like this:
Circle* shapeToLookup = NULL;
int idNum = 12;
database.lookup(idNum, circleToLookup);
if(circleToLookup != NULL)
{
// Do stuff with the circle.
}
and have the database know the type of its argument. Is there a way to do this without either overloading the function (lookup(int, Circle*), lookup(int, Rect*), ad nauseum)? Can you declare a function like lookup(int, Shape*) and have it know which type it’s given?
Thanks!
You can do it with a template.
Edit: new implementation based on the extra information. If
mymapis astd::map<int, Shape*>:Or you might prefer:
Then call it like
Circle *circle = database.lookup<Circle>(123);Obviously polymorphic containers are a whole heap of fun in themselves, but I’ll assume you have that sorted. There may well be a
shared_ptrin there somewhere that I’ve left out.Old implementation when I thought the DB might store copies of POD:
type_constant is an example of “type traits”, you implement it like: