Javas class <?> Equivalent in C ++
So, I am learning C ++ and want to write an entity system. To do this, I need to know what type the component has when I add it to the object. In java, I would just do something like this:
Class<?> someClass = myComponent.class;
Is there something equivalent in C ++? I tried typeid (myComponent), but this does not work in such situations.
ExtComponent* extended = new ExtComponent();
Component* base = dynamic_cast<Component>(extended);
std::cout << typeid(base).name();
This returns a "Component class", but I would like something that returns an "ExtComponent class" in such a situation. How to do it.
If you correctly understood that you want to receive a dynamic type of object. (not the type of the variable itself, but what this variable belongs to (really)
Typeid will work because:
N3337 5.2.8 / 2:
typeid glvalue , (10.3), std:: type_info, (1.8) (, type), glvalue [...]
, (, ), , , .
typeid , ( type_info , ):
Base *b = new Base;
...
typeid(*b); //not typeid(b)
. . ++. , , .
, , , . , :
template<typename>
void type_id(){}
using type_id_t = void(*)();
. std::any, boost::any, ++ 17.
struct Entity {
template<typename T>
void assign(T component) {
components[type_id<T>] = component;
}
template<typename T>
T& retrieve() {
return std::any_cast<T>(components[type_id<T>]);
}
private:
std::map<type_id_t, std::any> components;
};
. :
Entity entity;
entity.assign(MyClass{});
MyClass& mc = entity.retreive<MyClass>();
. , , .