Search code examples
c++templatestype-deduction

Accessing datamembers of template types


I have several POD structs, all who have a common datafield uint32_t gID.

struct component1
{
   uint32_t ID;
   //Other data
};

struct component2
{
   uint32_t ID;
   //Other data
};

struct component3
{
   uint32_t ID;
   //Other data
};

I would manage the POD structs with a factory class.

template <class Component>
class ComponentFactory
{
    public:
    //Activating/Deactivating components
    private:
    array<Component, 65536> m_components;
};

Now, the location in the m_components array is not always the same as the components ID. How could I write a function for ComponentFactory to return the ID of a component at some index? For example,

uint32_t ComponentFactory::getIDatIndex(uint16_t index) 
{
    //Grab the ID of whatever component the factory manages.
    return m_components[index].ID;
}

Additionally, is it possible to make the ComponentFactory typesafe so that there would not be ComponentFactory<int> or ComponentFactory<char>?


Solution

  • What you have works fine, after correcting the template syntax.

    template <class Component>
    uint32_t ComponentFactory<Component>::getIDatIndex(uint16_t index) 
    {
        //Grab the ID of whatever component the factory manages.
        return m_components[index].ID;
    }