对不起,如果这个问题有点混乱。我真的在寻求学习的目的,看看是否有这样的方式,甚至是可能的。跨多个班级成员功能共享模板参数
在下面的类,我要指定的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()返回一个指向父类型的指针。“*看起来像一个糟糕的设计。 – Pubby
这看起来不安全。 – Wug
ObjectManager如何在内部存储对象?它是否将所有对象存储在一张地图中,或者放在不同的地方?它可以从ID中推断出对象类型吗? –