6

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?

6
  • Don't fall into the trap of using RTTI (e.g. typeid) for this. You will regret it when you find you can't read your saved game info after recompiling.
    – sehe
    Nov 6, 2011 at 23:37
  • @sehe typeid is what I was afraid of running into! Haha
    – MGZero
    Nov 6, 2011 at 23:42
  • Are you sure that you don't want to use Boost.Serialize for this? If you're only ever going to save/load this data from a file, then it's more than likely the best solution. It even allows versioning and non-intrusive mechanics. Nov 6, 2011 at 23:42
  • @Nicol Bolas I actually haven't familiarized myself that much with Boost for some odd reason. If you could post an example, that would be great! :)
    – MGZero
    Nov 6, 2011 at 23:46
  • @MGZero: the documentation for Boost Serialization has a list of samples, introduced with proper explanation. It's kind of hard to tell what you will be needing without knowing more about your type hierarchy. I recommend you look for yourself. No boost library has ever cost me more than a day's worth of fiddling to get started. (Well, except the more abstract ones, like Boost MPL, Boost Proto and perhaps Boost Spirit; they did require some real learning curve IMO)
    – sehe
    Nov 7, 2011 at 0:01

2 Answers 2

7

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]();
7
  • Since the user didn't ask for a C++11 solution, perhaps you could remove the C++11 bits, so we could see what the type of classes is. Nov 6, 2011 at 23:34
  • this looks a bit like what Boost Serialization uses (of course much more complicated - sic) to register serializable types.
    – sehe
    Nov 6, 2011 at 23:35
  • @NicolBolas: classes would actually be of type std::initializer_list<CBaseTheoryEnt*()>. Mmm.
    – sehe
    Nov 6, 2011 at 23:36
  • I like this. Quick, clean and to the point. I'll wait a little bit on accepting the answer to see what others think. Much appreciated!
    – MGZero
    Nov 6, 2011 at 23:41
  • @sehe: No it would not, since the user asked for C++, not C++11. It would be a compiler error, which is why I asked for a more portable answer. Nov 6, 2011 at 23:41
1

You don't give too many specifics, so here's a fairly general approach using a map that might apply:

struct Base
{
  virtual int ID() const = 0;
  // ...
};

typedef Base * (*create_fp)();
typedef std::map<int, create_fp> create_map;

class DerivedA : public Base { /* ... */ };
class DerivedB : public Base { /* ... */ };
class DerivedC : public Base { /* ... */ };

namespace BaseCreators
{
  DerivedA * makeA() { /* ... */ }
  DerivedB * makeA() { /* ... */ }
  DerivedC * makeA() { /* ... */ }
}

const create_map creators {
  { 1, BaseCreators::makeA },
  { 2, BaseCreators::makeB },
  { 3, BaseCreators::makeC }
};

int main()
{
  int a = get_id_from_user();
  create_fp cr = creators.find(a)->second; // or check for existence first
  Base * b = cr();
}

(If you don't have C++11, you'll have to make the creators map non-constant and populate it manually.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.