Bizarre static_cast trick?
Posted
by Rob
on Stack Overflow
See other posts from Stack Overflow
or by Rob
Published on 2010-06-08T08:32:06Z
Indexed on
2010/06/08
8:32 UTC
Read the original article
Hit count: 178
While perusing the Qt source code I came across this gem:
template <class T> inline T qgraphicsitem_cast(const QGraphicsItem *item)
{
return int(static_cast<T>(0)->Type) == int(QGraphicsItem::Type)
|| (item && int(static_cast<T>(0)->Type) == item->type()) ? static_cast<T>(item) : 0;
}
Notice the static_cast<T>(0)->Type
? I've been using C++ for many years but have never seen 0 being used in a static_cast before. What is this code doing and is it safe?
Background: If you derive from QGraphicsItem
you are meant to declare an unique enum value called Type
that and implement a virtual function called type
that returns it, e.g.:
class Item : public QGraphicsItem
{
public:
enum { Type = MAGIC_NUMBER };
int type() const { return Type; }
...
};
You can then do this:
QGraphicsItem* item = new Item;
...
Item* derivedItem = qgraphicsitem_cast<Item*>(item);
This will probably help explain what that static_cast is trying to do.
© Stack Overflow or respective owner