【发布时间】: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<int> 或 ComponentFactory<char>?
【问题讨论】:
-
...你试过了吗?以上应该可以正常工作。它是鸭子类型,因此没有一种很好的方法可以使其类型安全。 en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29 试图解决这个问题,但它从未发生过。还有其他使用 typetraits、SFINAE 和/或专业化的方法,但我个人只是添加一条评论说“必须是一个组件”,然后就结束了。
-
array<Component, 65536> m_components;where Component 类型不同,栈内存有限,根本不起作用
标签: c++ templates type-deduction