【发布时间】:2012-10-24 19:50:38
【问题描述】:
对不起,如果这个问题有点令人困惑。我真的要求学习目的,看看是否有办法实现这一点。
在下面的类中,我必须为 CreateObject() 和 GetObject() 指定一个模板参数:
class ObjectManager
{
public:
template <class T>
void CreateObject(int id)
{
//Store pointer to newly created object in a map
}
template <class T>
T* GetObject(int id)
{
//Find object using id and return a T* to it
}
};
CreateObject() 使用模板参数创建正确类型的对象,然后将指向它的指针存储在映射中。 GetObject() 使用模板参数返回所需类型的指针。对于某些对象,我希望 GetObject() 返回指向实际对象类型的指针。对于其他对象,我希望 GetObject() 返回一个指向父类型的指针。
到目前为止,任何时候我调用 GetObject(),我都需要指定类型:
SomeType* pST = m_objectManager.GetObject<SomeType>(id);
AnotherType* pAT = m_objectManager.GetObject<AnotherType>(id);
我的目标是在我的 CreateObject() 函数中指定实际的对象类型和所需的返回类型作为模板参数:
class ObjectManager
{
public:
template <class T, class DesiredReturnType>
void CreateObject(int id)
{
//Store pointer to newly created object of type T in a map
//The DesiredReturnType would be used by GetObject() to return the correct type of pointer
}
//This isn't possible but would be ideal.
DesiredReturnType* GetObject(int id)
{
//Return a DesiredReturnType* to the object
}
};
m_objectManager.CreateObject<SomeType, ParentOfSomeType>(id);
//Now I don't need to specify a template argument when calling GetObject().
//CreateObject() will create a new SomeType.
//GetObject() will return a ParentOfSomeType* which is really pointing to a SomeType object
ParentOfSomeType* pPST = m_objectManager.GetObject(id);
由于每个对象都有不同的类型和不同的期望返回类型,我将无法使用类模板参数。类型和所需的返回返回类型总是会根据我创建的对象类型而变化。
这样的事情可能吗?是否有某种设计模式可以在这种情况下有所帮助?
编辑:
设计选择的原因如下。我将调用另一个具有不同行为的函数,具体取决于接收的是 Parent* 还是 Child*。
通过取出模板参数,我认为我可以做这样的事情:
for(int id = 0; id < 10; id++)
MyFunction(m_objectManager.GetObject(id));
这可能不会改变这是一个糟糕的决定选择的事实,但我主要是出于好奇而询问。 :)
【问题讨论】:
-
“对于某些对象,我希望 GetObject() 返回指向实际对象类型的指针。对于其他对象,我希望 GetObject() 返回指向父类型的指针。” 似乎是一个糟糕的设计。
-
ObjectManager 内部如何存储对象?它是将所有对象存储在一张地图中还是不同的地图中?是否可以从 ID 推断出对象类型?