在指向基数的指针的向量中找到派生类的第一个实例的“更干净”的方法吗?]

问题描述 投票:0回答:2
在我的游戏引擎中,我目前正在尝试简化代码:

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参数派生的类型:使用的整数...

c++ templates base derived
2个回答
2
投票
替代方法是使用dynamic_cast

2
投票
使用返回的指针时,您的方法具有未定义的行为,因为reinterpret_cast通常无法在继承层次结构中强制转换指针。仅当派生对象为带有基类对象的pointer-interconvertible时,它才会做正确的事情。尤其是只有standard-layout类和带有虚函数的类永远都不是标准布局的情况。 reinterpret_cast不会更改指针的地址,只是

reinterprets

© www.soinside.com 2019 - 2024. All rights reserved.