如何避免使用模板类型的派生类进行多态性动态强制转换
How to avoid dynamic cast in polymorphism with derived class of template type
我有这个架构(简短版本):
class BaseBatch {
virtual ~BaseBatch(){};
};
template<class T>
class Batch : public BaseBatch
{
void draw(T* data) {
do something..
}
};
class BatchManager
{
private:
static std::vector<BaseBatch*> batches;
public:
template <class T>
static void placeData(T* data){
//Loop through the entire container
bool found = false;
for (auto&& b: batches())
if (b->get_type() == typeid(T)) {
dynamic_cast<Batch<T>*>(b)->draw(data);
found = true;
}
//If no bach found, create a new One
if (not found) {
batches.push_back(new Batch<T>);
}
}
};
问题是 placeData 函数每 1 次循环被调用多次(多次),我认为动态转换对性能来说是一个真正的痛苦,但无法弄清楚如何在不使用它的情况下解决这个问题。它真的有那么大问题还是我不应该打扰它并继续使用它?如果我应该避免它,你会有什么建议?谢谢
与其使用std::vector<Batch*>
请使用std::unordered_map<std::type_index, std::unique_ptr<BaseBatch>>
。要访问批处理,请使用batches.find(std::type_index(typeid(T)))
,然后将其static_cast
到Batch<T>*
。static_cast
没有运行时开销。若要创建新批处理,请使用std::type_index(typeid(T))
作为键。
dynamic_cast
的性能可能不是这里的问题。实际上,使用此解决方案调用typeid
可能与dynamic_cast
一样糟糕。真正的潜在收益是unordered_map
的查找速度,而不是遍历谁知道有多大的vector
的每个元素并尝试dynamic_cast
。
相关文章:
- 多态性和功能结合
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 多态性和动态铸造
- C++结合静态和动态多态性来创建"Hyper Polymorphism"?
- 动态多态性C++的替代
- 如何避免使用模板类型的派生类进行多态性动态强制转换
- 当我需要多态性时,如何避免动态分配
- 静态多态性与boost变体单访问者与多访问者与动态多态性
- 动态分配和多态性-c++
- 如何在使用动态多态性时避免指针
- 动态多态性和运算符重载的真实示例
- vtable(动态绑定)的C++思想中的多态性
- 避免编译时已知类型的模板冗长和动态多态性
- 为什么AbstractFactoryUnit具有动态多态性而不是静态多态性
- 使用模板的动态多态性行为
- c++中的动态多态性和函数重载
- c++代码中的动态多态性错误
- CRTP和动态多态性编译错误
- 在这种情况下如何使用动态多态性
- 结合了静态多态性和动态多态性