访问模板类型的数据成员

Accessing datamembers of template types

我有几个 POD 结构,它们都有一个共同的数据字段 uint32_t gID

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

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

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

我会用工厂管理 POD 结构 class。

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

现在,m_components 数组中的位置并不总是与组件 ID 相同。我如何为 ComponentFactory 编写函数以 return 某个索引处的组件 ID? 例如,

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

此外,是否可以使 ComponentFactory 类型安全,这样就不会有 ComponentFactory<int>ComponentFactory<char>

在更正模板语法后,您的工作正常。

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;
}