How to call the right function based on only runtime typeIDs at runtime?

  c++, templates

I have a problem where I can add and remove objects of different types to another type, and I need to be able to know how to build, destroy, copy etc these objects from a typeID at runtime:

#include <vector>

int ComponentTypeCounter = 0;

template <typename T>
std::vector<T> components; // Each component type has a vector

struct Entity
{
    template <typename T>
    void addComponent()
    {
        static int componentTypeID = ComponentTypeCounter++;
        // Pair is a: componentIDType and b: position in vector
        std::pair<int, int> compInfo{ componentTypeID, components<T>.size() };
        this->ownedComponents.push_back(compInfo);
        
        components<T>.push_back(T()); 
        
    }
    ~Entity()
    {
        for (auto& comp : this->ownedComponents)
        {
            // All we have here to remove from the right components vector is the componentTypeID
        }
    }

    std::vector<std::pair<int, int>> ownedComponents;
};


struct VelocityComponent {};
struct PositionComponent{};
struct SoundComponent {};
struct IsAnimalComponent { ~IsAnimalComponent() { std::cout << "IsAnimalComponent being destroyedn"; } };


int main()
{
    Entity ent1;
    ent1.addComponent<SoundComponent>();
    ent1.addComponent<PositionComponent>();
    ent1.addComponent<VelocityComponent>();
    
    //ent1.removeComponent<VelocityComponent>(); // Removing a known type at compile time isn't a problem

    {
        Entity ent2;
        ent2.addComponent<PositionComponent>();
        ent2.addComponent<IsAnimalComponent>();
    }
        // On destruction all ent2 knows is that it has a (1) component, and a(3) component
        // It cannot reach the right vector to remove the component because it only has the //componentTypeID
        // at runtime.
}

Source: Windows Questions C++

LEAVE A COMMENT