I have written the following class to allow me to uniquely identify classes in C++, and I was wondering if there are any better ways of going about it.
#ifndef _TYPE_IDENTIFIER_H_
#define _TYPE_IDENTIFIER_H_
typedef std::size_t Identifier;
class TypeIdentifier {
public:
template<class T>
static Identifier get_identifier() {
static const Identifier current_identifier = ++next_identifier;
return current_identifier;
}
private:
static Identifier next_identifier;
};
Identifier TypeIdentifier::next_identifier = 0;
#endif
And an example of using it:
class MyFirstClass {};
class MySecondClass {};
printf("%zu", TypeIdentifier::get_identifier<MyFirstClass>()); // 1
printf("%zu", TypeIdentifier::get_identifier<MySecondClass>()); // 2
printf("%zu", TypeIdentifier::get_identifier<MySecondClass>()); // 2
printf("%zu", TypeIdentifier::get_identifier<MyFirstClass>()); // 1
I'm using it in an ECS, where there can only be one instance of a certain component in an Entity. I store a vector of structs containing a void pointer to the component and an Identifier type of the component. Using TypeIdentifier::get_identifier<ComponentType>(), I can check the type of a passed component and check if it's already present in the Entity.
MyFirstClassis 1 and the type ID ofMySecondClassis 2 (or the other way round, depending on the order of invocation). \$\endgroup\$