C++ 中的高效运行时类型检查 [英] Efficient run-time type checking in C++
问题描述
我有两个名为Expression"和BinExp"的类,代码如下:
I've two class named 'Expression' and 'BinExp' as following codes:
class Expression
{
public:
virtual BinExp* IsBinaryExp() { return NULL; }
};
class BinExp : public Expression
{
public:
virtual BinExp* IsBinaryExp() { return this; }
};
例如,我有一个 Expression*
的指针变量类型,但初始化为 new BinExp
并作为参数发送给 analysis
函数如下代码:
As example, I've a pointer variable type of Expression*
but initialized as new BinExp
and send as argument to a analyse
function as following code:
int main()
{
Expression* e = new BinExp;
analyse(e);
}
在analysis
函数内部,我需要知道e
是指向Expression
类型还是BinExp
类型.在我看来,有三种方法可以做到这一点.
Inside the analyse
function, I need to know whether the e
is pointer to Expression
type or BinExp
type. In my hand, there is three way to do this.
首先:
BinExp* be = e->IsBinaryExp();
if ( be )
{
printf("Yes, `e` is a binary expression\n");
}
第二:
BinExp* be = dynamic_cast<BinExp*>(e);
if ( be )
{
printf("Yes, `e` is a binary expression\n");
}
第三个:
if ( typeid(*e) == typeid(BinExp) )
{
BinExp* be = e->IsBinaryExp(); // or dynamic_cast<BinExp*>(e);
printf("Yes, `e` is a binary expression\n");
}
但是我想知道当我需要在性能很重要的循环中频繁执行检查时,哪种方式(或任何其他方式)会更高效和有效.任何形式的建议我都会很感激.
But I want to know which of those ways ( or any other ) will be more efficient and effective when I need to perform the checking frequently inside a loop where performance is a matter. Any kind of suggestion I will appreciate.
推荐答案
最快的方法是保留一个成员变量,比如一个 enum ,然后在基类中定义一个内联 getter,然后你可以比较结果是否是你期望什么.
The fastest way would be to keep a member variable , say an enum , then define in the base class a inline getter, then you can compare if the result is what you expect.
示例(未编译,可能会出现一些错误):
Sample (uncompiled, some errors might occur) :
enum eExpTypes {
ET_UNDEFINED,
ET_BINARY
}
class Expresion
{
protected:
eExpTypes myType;
public:
Expresion(): myType(ET_UNDEFINED){};
inline eExpTypes getType(){return myType;};
}
class BinExpresion : public Expresion
{
public:
BinExpresion():myType(ET_BINARY){};
}
性能提升:
- 你将取出两个指示:从指针到 vfptable ,从 vfptable 到函数
- 如果类型函数是唯一的虚函数,你的类大小会更小
动态转换通常比创建您自己的类型检查机制要慢,因此对于您的 3 个示例,第一个应该是最快的.
Dynamic cast is usually slower then making your own type check mechanism, so in case of your 3 examples the first one should be the fastest.
这篇关于C++ 中的高效运行时类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!