0

I'm currently working on an entity-component system in which I need to create unique IDs for different component types, preferably without storing any additional data in the component class (as that would require static virtual methods, which don't work, and so I would need to instance a new component every time I compare something). The approach I ended up going with was creating a templated method:

/*statically instances unique pointers for different
TComponents - each with their own templated instance*/

template<typename TComponent>
static const COMP_ID& GetTComponentID()
{
    DERIVES_FROM_COMPONENT_ASSERT;

    static COMP_ID ID = Component::NewID();
        
    return ID;
}   

and then have a static method in my component base class which returns a unique ID every time a new static COMP_ID is initialized in GetTCompomponentID():

//retrieves static data identifier

static const COMP_ID& NewID()
{
    static COMP_ID currID = 0; 
    currID++;

    return currID;
}

Using this, I can create unique, static IDs for each component derivative which I use without needing to store the data in the class itself as a virtual function (which can't be static, so every time a comparison is needed it would require a new instance)

Are there any underlying issues to using a system like this except the obvious extra memory utilized by the static method members?

-thanks

Its Me
  • 174
  • 1
  • 8
  • if you are ok with function local static variable you could as well use a non-static virtual method with a local static ID. – 463035818_is_not_an_ai Mar 16 '21 at 14:59
  • The problem is that I would like to access my components' IDs by stating the component type to a method and it returning it. While a static method like that could work it wouldn't really be enforced in the derived classes, additionally that would require more code per-component while this only requires two methods – Its Me Mar 16 '21 at 15:18
  • Is your solution required to be thread-safe? If not, then `static` local variables are overkill as they are always protected by a mutex/atomic flag. More details [here](https://stackoverflow.com/a/52202005/485343). – rustyx Mar 16 '21 at 15:37
  • No, I don't need it to be thread-safe at the moment. The issue is that this is, so far, the only way I could think of to access component IDs statically via a typename and for them to remain constant between all classes once established – Its Me Mar 16 '21 at 15:44
  • 1
    You could use `std::type_index(typeid(T))` if you need a unique type ID, this should give no runtime overhead. In most cases it's equivalent to `(uintptr_t)&typeid(T)`. – rustyx Mar 16 '21 at 16:41
  • Thank you, that's definitely a cleaner solution than what I had before – Its Me Mar 16 '21 at 19:24

0 Answers0