0

So I have a templated function that I want to define the type dynamically.

something_that_holds_type type;
obj.GetComponent<type>();

Is it possible? I also thought of smothing like this:

#define GETTYPE(t) t
obj.GetComponent<GETTYPE(int)>();

This works, but that doesn't help. What I would like to do was to pass the type name and converte it into a keyword, similar to this:

#define GETTYPE(t) removes_quatation_marks_of_t
obj.GetComponent<GETTYPE("int")>();

Is any of this possible in c++?

Corelli
  • 21
  • 6
  • 7
    What exactly are you trying to achieve by doing this? The type has to be known at compile time anyway, so these macros just seem to make things more difficult – UnholySheep Dec 28 '19 at 23:21
  • Just write `int` bro – Lightness Races in Orbit Dec 28 '19 at 23:22
  • 3
    Tell us what you're _really_ trying to do. Something like a `std::variant` may be of use to you but we have no way of knowing really – Lightness Races in Orbit Dec 28 '19 at 23:26
  • [`std::type_info`](https://en.cppreference.com/w/cpp/types/type_info) (in [`#include `](https://en.cppreference.com/w/cpp/header/typeinfo)) and `typeid(Foo)` may do what you want. Not cross-compiler compatible, if you want to share across platforms or for persistent storage. – Eljay Dec 28 '19 at 23:30
  • I have a class Entity class. That class can have and access just one component at the time: Box Collider, Sphere Collider, Mesh Collider etc. But I wouldn't like declare every collider component that I could have in the Entity class. So I've created a void* that points to one of the collider classes. In order to access the data correctly I have to know the types at runtime as I plan to chage the collider at runtime too. I want a function that returns a pointer to the collider, thats' beacause I have a template – Corelli Dec 28 '19 at 23:45
  • @Corelli Then you should use `std::variant`, polymorphism or the visitor pattern or some of the other language tools to deal with that kind of situation. – super Dec 28 '19 at 23:54
  • @Corelli It seems that you want runtime polymorphism via virtual member functions. `Collider` would be a base class with virtual destructor and virtual interface. The specific `Collider` types will be derived from it and implement the virtual interface. `Entity` will take a `Collider*` (or `std::unqiue_ptr` if owning) instead of a `void*` and then you won't ever need to know the actual object's type inside `Entity`. – walnut Dec 28 '19 at 23:55

1 Answers1

0

No what you describe cannot be done.

Variations of what you ask can be done, but to describe it we'd have to see something more concrete than your abstract description.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524