samedi 10 juin 2023

Map Enum Values with Template Type

NOTE: I've seen a lot of answers on this topic, but the problem is that I don't quite understand how metaprogramming works, although I've used it in some way. Therefore, I would like to get an answer for my case. Don't judge strictly. :)

Main Issue:

First i've have simple enum where i store the ComponentTypes like this:

typedef enum ComponentType {
   ComponentType_ID,
   ComponentType_Editor,
   ComponentType_Tag,
   ComponentType_Transform
} ComponentType;

Second i've have struct's for each of this component type:

struct Component  {
};

struct IDComponent : public Component {
};

struct EditorComponent : public Component {
};

struct TagComponent : public Component {
};

struct TransformComponent : public Component {
};

I can do conversion only from template type to enum types like this:

template<typename T>
constexpr ComponentType ComponentTypeFromTemplate() {
if (std::is_base_of_v<Component, T>) {
    if      (std::is_same_v<T, IDComponent>)               return ComponentType_ID;
    else if (std::is_same_v<T, EditorComponent>)           return ComponentType_Editor;
    else if (std::is_same_v<T, TagComponent>)              return ComponentType_Tag;
    else if (std::is_same_v<T, TransformComponent>)        return ComponentType_Transform;
}

But how i can convert enum ComponentType types to template type specific?

or

How i can map this types with enum types using metaprogramming and templates, so i can return the template type using function and trailing return types?

And use something like this:


constexpr ComponentType type = ComponentType_ID;
using T = ComponentTypeToTemplate(type); // do some magic to get T

if constexpr(std::is_same<T, IDComponent>)
   std::cout << "IDComponent is currect" << std::endl;

constexpr ComponentType type2 = ComponentType_Transform;
using T2 = ComponentTypeToTemplate(type2); // do some magic to get T

if constexpr(std::is_same<T2, TransformComponent>)
   std::cout << "TransformComponent is currect" << std::endl;

Aucun commentaire:

Enregistrer un commentaire