How to dereference to the derivied class?/How bad is it of my currently way of doing it?

Started by
7 comments, last by Conny14156 9 years, 10 months ago

Hi,

I have a map like this were I store deriviedclass pointers inside a basepointer


std::map<std::string,BaseComponent*> componentMap;

I was wondering if there were any "smart" way to dereference it to the derivied class?

my current way is


template<class T_S>
T_S* GetComponent()
{
	std::string test = typeid(T_S).name();
	std::map<std::string, BaseComponent*>::iterator it;
	for (int i = 0; i < 6; i++)
	{
		test.erase(test.begin());
	}
	it = componentMap.find(test);
	if (it != componentMap.end())
	{
		T_S* ptTComponent;
		ptTComponent = (T_S*)it->second;

		return ptTComponent;
	}
	else
		return NULL;
}

I use typeid to get the class "name", and the string is ctrl + c and ctrl + v, but I want some more "safe?" way to get the class name.

Advertisement

One way is the so called CRTP (curiously recurring template pattern), where you seperate your component class in one normal base class, and one templates class, like this:


class BaseComponent
{
public:

    virtual ~BaseComponent(void) = 0 {};
    
    static unsigned int GenerateId(void)
    {
        return m_typeCounter++;
    }
    
private:

    static unsigned int m_typeCounter; // define & init this in cpp-file to 0
}

template<typename>
class Component :
    public BaseComponent
{
public:
    static unsigned int Type(void)
    {
        static const type = GenerateId();
        return Type;
    }
}

Now you declare your component-classes so:


class MyComponent :
	public Component<MyComponent>
{
}

and then you can write your function to call "::Type()" on the templates component type, which will return the runtime-fixed type-id of the component-type, which you can use for safe map lookup of the component. Note that things get a little more compicated once you want to use components of the same types across dlls, but I doubt that thats what you want to do right now.

EDIT: also note that this pattern is extremly useful as what you can already define in the "Component"-class, e.g. you can add a virtual Clone-method to the BaseComponent and override it in the Component-class, so that you don't have to define it for every component-child you declare.

When you are properly using inheritance you very rarely need to cast that way. The entire point of deriving from a base class is that code that uses it should never know what class is involved.

See also: Dependency Inversion Principle.

As described in that link, many game engines will provide and implement abstract interfaces. You program against the abstract interface. If you need something that does something, you search based on the abstract interface.

For an example, one major game I worked on, the concrete GameObject class derived from the IGameObject interface. You would not search for a GameObject, you would search for an IGameObject.

Doors and bridges and other portals implemented IHasPortal. It would be a very bad idea to try to search for a concrete instance because there were many classes of things that implemented IHasPortal. There were bi-directional doors and one-way gates and assorted kinds of bridges, drawbridges that could be opened and closed, and downloaded content meant new classes could be added that you would never know about. But if you always searched for objects implementing IHasPortal, you would get anything and everything.

We had quite a lot of them in the code base. IDetonatable, IStoreFront, INotCloneable, and so on.

Use a dynamic_cast and if it returns NULL, it doesn't implement the type. Be a tiny bit wary of using dynamic_cast. On many systems it is very nearly zero-cost, on other systems it has quite a high cost, plus it also depends on if you are searching up the inheritance tree or down it. If you are on one of those systems where dynamic_cast has a high cost, there are tricks you can use with type_id instead. GCC implements dynamic_cast so casting to the base class is optimized to basically the cost of a single pointer indirection, and since the interfaces are base classes, it is practically free.


When you are properly using inheritance you very rarely need to cast that way. The entire point of deriving from a base class is that code that uses it should never know what class is involved.

What you are talking about is inheritance, but when you are going a more composition-oriented approach, then I would slightly argue against you. In a data-oriented component-system, where each entity is composed of multiple components that are all POD, and there are systems that implement behaviour, there isn't even a think like IHasPortal - instead, the entity contains a "Portal"-component. In that case, you would want to cast in the way the OP does - its not casting a specify class, its casting a composite of the class, which is more than ok IMHO. (I'm of course skipping over the part that you should rather have all components of the same type in one array/vector anways, that would be bad for explanation purposes...)

I use typeid to get the class "name", and the string is ctrl + c and ctrl + v, but I want some more "safe?" way to get the class name.


Why do you need a name at all? Just use the typeinfo value itself. You can use either a map<typeinfo, Component*> or a map<const typeinfo*, Component*> (I don't remember if the former is legal). Don't do this across DLL boundaries, though.

You can use Juliean's approach, too, with a further trick to make it even safer (and to actually work in C++, which does not have static type constructors):


class Base {
public:
  virtual ~Base() = defualt;
  virtual const void* MyTypeId() const = 0;
};

template <typename T>
class DerivedHelper : public Base
{
public:
  virtual const void* MyTypeId() const override { static typeTag = 0; return &typeTag; }
};

class MyComponent : public DerivedHelper<MyComponent>
{
};
You never actually dereference the value returned by MyTypeId, but just use it as an opaque handle to a unique type. The ODR rules require that there be only a single copy of static typeTag so the address returned will always be the same. Again, barring cross-DLL boundaries. You can make this DLL safe by using some macros instead of templates and making sure you define the static value in a .cpp file and not in a .h file.

Sean Middleditch – Game Systems Engineer – Join my team!

The standard way of getting the derived pointer from the base is dynamic_cast:


Derived *derived = dynamic_cast<Derived*>(base); //Returns null on failure, just like your function.

.

Compilable example: [ideone.com]

[Edit:] frob mentioned dynamic_cast, I didn't notice that.


The standard way of getting the derived pointer from the base is dynamic_cast:

Derived *derived = dynamic_cast(base); //Returns null on failure, just like your function.

.

Compilable example: [ideone.com]



[Edit:] frob mentioned dynamic_cast, I didn't notice that.

dynamic_cast is not an option here, at least not a good one. I wanted to write this already yesterday to frobs post, but didn't realize why (it was too late already). In this example the OP has a container of all the same classes, say there is 12 objects in them, each of them unqiue in type. Performing dynamic_cast on all of them until you found the right one is quite wastefull, in comparison to just getting the typeid (eigther via RTTI or some customized system), getting the value with the entry and static-casting.


You can use Juliean's approach, too, with a further trick to make it even safer (and to actually work in C++, which does not have static type constructors):

Why wouldn't my approach work in C++? I'm curious, as I'm actually using it in my c++ game engine, and that quite often biggrin.png I mean, the typeid is not safe across different program starts, so it could happen that one time component "transform" has id 2 and the other time it is 4, but it still is relatively safe in the same execution. I find your approach interesting nevertheless, though for my components, I prefer my way, because due to the linear nature of the id-values I can use a vector for storing the components instead of a map

dynamic_cast is not an option here, at least not a good one. I wanted to write this already yesterday to frobs post, but didn't realize why (it was too late already). In this example the OP has a container of all the same classes, say there is 12 objects in them, each of them unqiue in type. Performing dynamic_cast on all of them until you found the right one is quite wastefull, in comparison to just getting the typeid (eigther via RTTI or some customized system), getting the value with the entry and static-casting.

Good point - I hadn't realizing he was using the type to search for or index the components! I mistakenly thought he already knew which Base* was the correct one. mellow.png

In that case, I'd also use a static ID - either linearly, or else a compile-time hash (using constexpr) of the component's type name, to keep the IDs constant from compiler to compiler, and from build to build.


static const uint32_t ID = compile_time_hash(#ComponentName);

The components would then be in a std::unordered_map, not a sorted map.

mind-blown.jpeg

So many complex word and method!

But will try to improve it from all the feedback!

I think I will go towards Juliean way with the CRTP method, it seems kind of fun. if I make it to work, I will try to improve it with SeanMiddleditch suggestion.

And I will remake my std::map to a std::unordered_map as Servant of the Lord suggested. if I got all the above to work

This topic is closed to new replies.

Advertisement