在C++中,"dynamic_cast"缓慢是一个众所周知的事实.我想到了以下简单的方法来了解层次结构中对象的类型.有人可以解释一下这是否比dynamic_cast慢?如果不是,那么为什么不是普遍的做法,因为速度的C++对C最差的缺点?
struct Base {
unsigned m_type;
Base(unsigned type): m_type(type) {}
Base(): m_type(0) {}
};
struct Derived1: Base {
Derived1(): Base(1) {}
Derived1(int type): Base(type) {}
};
struct Derived2: Base {
Derived2(): Base(2) {}
};
struct Derived3: Derived1 {
Derived3(): Derived1(3) {}
};
void my_func(Base * p) {
if (p - > m_type == 0) {}
else if (p - > m_type == 1) {}
else if (p - > m_type == 2) {}
else if (p - > m_type == …Run Code Online (Sandbox Code Playgroud)