C ++等价于instanceof [英] C++ equivalent of instanceof

查看:153
本文介绍了C ++等价于instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现 instanceof

解决方案

尝试使用:

  if(NewType * v = dynamic_cast< NewType *>(old)){
// old被安全地转换为NewType
v-> doSomething();
}

这需要您的编译器启用rtti支持。



编辑:
我对此答案有一些好的评论。



每次你需要使用dynamic_cast或instanceof)你最好问自己这是一个必要的事情。它通常是糟糕的设计的标志。



典型的解决方法是将您要检查的类的特殊行为放在基类的虚函数中,或者引入类似于访问者,您可以在不更改界面的情况下引入子类的特定行为(除了添加访问者接受界面当然)。



正如所指出的,dynamic_cast不是免费的。一个简单而始终如一的执行hack,处理大多数(但不是所有的情况)基本上是添加一个枚举代表你的类可以有的所有可能的类型,并检查你是否有正确的。

  if(old-> getType()== BOX){
Box * box = static_cast& >(old);
//做一些特定的盒子
}

这不好oo设计,但它可以是一个解决方法,其成本或多或少只是一个虚函数调用。它也工作,不管RTTI是否启用。



请注意,这种方法不支持多级别的继承,所以如果你不小心,你可能会结束代码看起来像这样:

  //这里我们有一个继承Box的SpecialBox类,因为它有自己的类型
//我们必须检查BOX或SPECIAL_BOX
if(old-> getType()== BOX || old-> getType()== SPECIAL_BOX){
Box * box = static_cast< Box *>(old);
//做一些特定的盒子
}


What is the preferred method to achieve the C++ equivalent of instanceof?

解决方案

Try using:

if(NewType* v = dynamic_cast<NewType*>(old)) {
   // old was safely casted to NewType
   v->doSomething();
}

This requires your compiler to have rtti support enabled.

EDIT: I've had some good comments on this answer!

Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design.

Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a visitor where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).

As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one.

if(old->getType() == BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}

This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.

Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:

// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}

这篇关于C ++等价于instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆