std::vector<Base*> bases; //An arbitrary vector of the abstract class Base.
/*
GetFromBase
param derivedType: An integer used for quick comparison between each derived.
return: A pointer to the first derived found, or nullptr if not found.
*/
template <typename T>
T* GetFromBase(int derivedType)
{
//Walk through each base
for (Base* b : bases)
{
//Check if its internal type is the same as the enum
if(b->GetDerivedType() == derivedType)
{
//Return the casted pointer
return reinterpret_cast<T*>(b);
}
}
//No derived of the desired type was found.
return nullptr;
}
是否可以仅使用模板参数来执行相同的功能,如果可以,对性能的影响是否很大?
在我的游戏引擎中,我目前正在尝试简化代码:std :: vector
bases; //抽象类Base的任意向量。 / * GetFromBase参数派生的类型:使用的整数...
dynamic_cast
reinterpret_cast
通常无法在继承层次结构中强制转换指针。仅当派生对象为带有基类对象的pointer-interconvertible时,它才会做正确的事情。尤其是只有standard-layout类和带有虚函数的类永远都不是标准布局的情况。 reinterpret_cast
不会更改指针的地址,只是reinterprets