jeudi 11 mai 2023

How can I unpack variadic template, so as to initialize respective members?

I am new to variadic templates and packed arguments and all. I want to have a "entity component system" in my program, and while trying to add component to the entity, I came to realize that my attempt has a major flaw.

Anyways here is my failed attempt.

struct A{
    float x;
    float y;
    
    A(float _x, float _y):x(_x), y(_y){}
};

struct B{
    float x;
    float y;
    float z;
    
    B(float _x, float _y, float _z):x(_x), y(_y), z(_z){}
};

struct Entity{
    A* a = NULL;
    B* b = NULL;
    
    Entity(){}
    
    template<typename T, typename... args>
    void Add(args... _args){
        if(typeid(T) == typeid(A))
            a = new A(_args...);
        else if(typeid(T) == typeid(B))
            b = new B(_args...);
        else
            throw("Invalid component added");
    }
};

And implementation looks like this..

Entity ent;
ent.Add<A>(12.24f, 123.246f);
ent.Add<B>(1.f, 1.2f, 1.23f);

I want the implementation to work somehow.. what has to be changed for it??

Aucun commentaire:

Enregistrer un commentaire