如何安全地向下转换(即在失败时返回 null)到底层对象的确切类型,而不会导致 dynamic_cast
的性能损失,并且不必在每个类中都放置支持代码用吗?
最佳答案
dynamic_cast
会遍历整个继承树,看看你想要的转换是否可行。如果您想要的只是直接向下转换为与对象相同的类型,并且您不需要交叉转换、跨越虚拟继承或转换为对象的实际类型,下面的代码将起作用:
template<class To>
struct exact_cast
{
To result;
template<class From>
exact_cast(From* from)
{
if (typeid(typename std::remove_pointer<To>::type) == typeid(*from))
result = static_cast<To>(from);
else
result = 0;
}
operator To() const
{
return result;
}
};
语义与其他强制转换运算符完全相同,即
Base* b = new Derived();
Derived* d = exact_cast<Derived*>(b);
编辑:我已经在我正在进行的项目中测试了这个。我从 QueryPerformanceCounter
得到的结果是:
dynamic_cast
:83,024,197
exact_cast
:78,366,879
这是一个 5.6% 的加速。这适用于非平凡的 CPU 绑定(bind)代码。 (它没有 I/O)
关于c++ - 避免 dynamic_cast 向下转换为原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11494524/