I’m trying to make a “component manager” class in C++ that is similar to the one found in Unity3d. What I want is a container class that can hold derived types of some class say BaseComponent. In unity, one can request for a component using generics in a type-safe way via
manager.GetComponent() which return type is DerivedComponentType&
I’d like the same interface in C++. This way, so long as components are added through a AddComponent function, the whole process is guaranteed to be type-safe from a usage standpoint.
I’m trying here to avoid things like identifying with strings. I realize I could also do this by giving every derived type a static member function of the same name and use the address of that as a map index to the class instances. I would rather not do this so that users of the component manager wont have to make sure this function exists should they ever choose to derive their own components.
Thanks.
One way you can do it is with dynamic_cast.
If the type doesn’t match what is given by the template, dynamic_cast will give a null pointer. Of course this is something that has to be done at runtime. On a modern machine this won’t be a huge hit unless you’re doing it way too often. There are a few other ways to do it that would be far more involved.
You could also look into writing a reflection system that gives a faster way to find type information, so that you have something like this:
This would be far more work in the long run, and would require doing some research on your part, but it is perhaps the only c++ option I know of that doesn’t require the use of string lookup and the “dreaded” dynamic_cast so many people tend to hate.