开发者

Static cast in middle of inheritance chain

Suppose we have:

class Component : public QGraphicsItem {
   ...
   virtual void paintMe() = 0;
   virtual void doSomething();

   virtual bool isComposite() const { return false; }
}

class Composite: public Component {
   ...
   void addChildren(Component *);
   void removeChildren(Component *)

   bool isComposite() const { return true; }
}

class IconNode: public Composite {
  ...
  void paintMe();
}

class ImageNode: public Composite {
  ...
  void paintMe();
}

The question is: Is following example safe, if I can guarantee that item is always some class that inherits Composite?

void test (开发者_开发技巧Component *item) {
  if (item.isComposite()) {
    Composite *comp = static_cast<Composite*>(item);
    ...
  }
  ...
}

I know that this is a little bit strange example, since I could use dynamic_cast for safety, but I was wondering if it can be done with static_cast.

Background: I am having troubles with Qt Graphics View Framework. Namely, it has functions T qgraphicsitem_cast ( QGraphicsItem * item ) which casts items to original class (e.g. IconNode -> IconNode, Compsite -> Composite), but it can't cast to class in the middle of inheritance chain (IconNode -> Composite) since it recognizes the classes by using function type() and because type() for IconNode and Composite is different the conversion fails.

This can be solved by following example, but I am wondering if my previous example could do the job safely:

Composite * castItem (QGraphicsItem *item) {
  if (item != 0) {
    switch(item.type()) {
      case IconNode::Type:
        return qgraphicsitem_cast<IconNode*>(item);
      case ImageNode::Type:
        return qgraphcisitem_cast<ImageNode*>(item);
    }
  }
  return 0;
}


The simple answer is: yes, if you know it is something, you can static_cast to it safely.


dynamic_cast is pretty much just

  1. check type for compatibility
  2. use static_cast if ok, return null/throw badcast otherwise
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜