【问题标题】:Accessing datamembers of template types访问模板类型的数据成员
【发布时间】:2015-01-21 20:10:21
【问题描述】:

我有几个 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 结构。

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

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

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

另外,是否可以使 ComponentFactory 类型安全,这样就不会出现 ComponentFactory&lt;int&gt;ComponentFactory&lt;char&gt;

【问题讨论】:

  • ...你试过了吗?以上应该可以正常工作。它是鸭子类型,因此没有一种很好的方法可以使其类型安全。 en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29 试图解决这个问题,但它从未发生过。还有其他使用 typetraits、SFINAE 和/或专业化的方法,但我个人只是添加一条评论说“必须是一个组件”,然后就结束了。
  • array&lt;Component, 65536&gt; m_components; where Component 类型不同,栈内存有限,根本不起作用

标签: c++ templates type-deduction


【解决方案1】:

在更正模板语法后,您所拥有的一切正常。

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

【讨论】:

  • 我明白了!我不认为它会起作用,看到我认为它根本不知道。但是,我现在看到它在编译时推断,因此将“知道”请求的方法/数据成员是否存在。
猜你喜欢
  • 2020-08-23
  • 2018-09-18
  • 2017-11-27
相关资源
最近更新 更多