So I've been learning about Entity Component Systems(ECS) and came across this method for creating unique ID's by passing the object as a template parameter. I was wondering how the line:
static ComponentID typeID{getUniqueComponentID()};
is creating ID's without having a duplicate ID created again. I know it's probably glaringly obvious.
Here's the entire code that works and doesn't repeat any ID's
#include <iostream>
using ComponentID = std::size_t;
//Creates a unique ID for and component that is created
inline ComponentID getUniqueComponentID() noexcept{
//states that the static ComponentID is going to start at 1
static ComponentID lastID{1u};
std::cout<< "Created ID: " << lastID << std::endl;
return lastID++;
}
//gets the component ID of the Type that is being passed into template
template<typename T>
inline ComponentID getComponentTypeID() noexcept{
//ComponentID is tied to the templated object type
static ComponentID typeID{getUniqueComponentID()};
return typeID;
}
struct A{};
struct B{};
struct C{};
int main(int argc, const char * argv[]) {
std::cout << getComponentTypeID<A>() << std::endl;
std::cout << getComponentTypeID<B>() << std::endl;
std::cout << getComponentTypeID<C>() << std::endl;
std::cout << getComponentTypeID<C>() << std::endl;
/*
Output:
1
2
3
3
*/
return 0;
}
Aucun commentaire:
Enregistrer un commentaire