C ++ Call a specific function if the type is a derived type

advertisements

I have a wide variety of small component structs with wildly different signatures, data, etc.

struct A, struct B, struct C.

Usually, I'd like each to have a system class free each of these types using templates:

static void Free(Component<T>* c)
{
    if (c)
    {
        staticDataPool->Free(c);
    }
}

These would correspond to pools created with templates of types A, B, and C.

What I'd like to do is derive a few of them from DestroyableComponent such that when Free() is called. All DestroyableComponents would have a virtual function called Destroy().

static void Free(DestroyableComponent* d)
{
    if (d)
    {
        d->Destroy();
        staticDataPool->Free(d);
    }
}

In the end, if the class is derived from DestroyableComponent it calls the second version of Free(), if it's not it calls vanilla Free().

Is there a way to do this without all component structs having to derive from something?


Free(Component<T>* c)
{
     DestroyableComponent* p = dynamic_cast<DestroyableComponent>(c);
     if(p == NULL) //p is not destroyable
     {
          //free static stuff
     }
     else
     {
          //free destroyable stuff
     }
}

May I also add that run-time type conversion (RTTI) is slow, so I would seriously think about your design. If I need to detect an object that was allocated on the heap, I overload new and delete for the class, and add a bool destroyable. If delete sees the object is destroyable, it deallocates. Otherwise, it does nothing.