Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping an ID number to a class

Tags:

c++

class

I'm setting up a system where I can instantiate classes on the fly based on some information read in from a file. So, this has to be done on runtime. The classes in question are polymorphic and all inherit from the CBaseTheoryEnt class. What I want to do is associate an ID number with each class (with an unordered map for example). Essentially, my management class is going to look at a series of these ID numbers read in from the input file and then instantiate the appropriate classes. What would be an ideal and efficient way of associating the classes with the ID and then instantiating them based on the input?

like image 592
MGZero Avatar asked Nov 06 '11 23:11

MGZero


1 Answers

One way to do this is to have a template function to instantiate the subclasses of CBaseTheoryEnt:

template<typename T>
CBaseTheoryEnt* instantiator() {
    return new T;
}

Then have a hash_map or array of these functions for each class that is derived from CBaseTheoryEnt and have the key for that class be associated with the instantiator for it. Then when you index the array or map, you get a function which, when called, will return a pointer to an instance of the appropriate class.

For instance, if you had classes A, B, and C, and the id for A was 0, for B was 1, and C was 2, you'd have:

typedef CBaseTheoryEnt* (*instantiator_ptr)();
instantiator_ptr classes[] = {
    &instantiator<A>,
    &instantiator<B>,
    &instantiator<C>
};

Then use it like

int idx = get_class_id();

CBaseTheoryEnt* inst = classes[idx]();
like image 104
Seth Carnegie Avatar answered Oct 13 '22 00:10

Seth Carnegie