Bizarre static_cast trick?

This is a common trick to use protected(static) members from outside the (sub)class. A better way would have been to expose some method, but since it wasn't intended to be user class they let go the hard work?!!


The current standard and the draft for the upcoming standard suggest that dereferencing a null pointer is undefined behaviour (see section 1.9). Since a->b is a shortcut for (*a).b the code looks like it tries to dereference a nullpointer. The interesting question here is: Does static_cast<T>(0)->Type actually constitute a null pointer dereference?

In case Type was a data member this would definitely be dereferencing a nullpointer and thus invoke undefined behaviour. But according to your code Type is just an enum value and static_cast<T>(0)-> is only used for scoping / name lookup. At best this code is questionable. I find it irritating that a "static type property" like a local enum value is accessed via the arrow operator. I probably would have solved it differently:

typedef typename remove_pointer<T>::type pointeeT;
return … pointeeT::Type … ;

This looks like a very dubious way to statically assert that the template parameter T has a Type member, and then verify its value is the expected magic number, like you state you are supposed to do.

Since Type is an enum value, the this pointer is not required to access it, so static_cast<Item>(0)->Type retrieves the value of Item::Type without actually using the value of the pointer. So this works, but is possibly undefined behavior (depending on your view of the standard, but IMO a bad idea anyway), because the code dereferences a NULL pointer with the pointer dereference operator (->). But I can't think why this is better over just Item::Type or the template T::Type - perhaps it's legacy code designed to work on old compilers with poor template support that couldn't work out what T::Type is supposed to mean.

Still, the end result is code such as qgraphicsitem_cast<bool>(ptr) will fail at compile time because bool has no Type member enum. This is more reliable and cheaper than runtime checks, even if the code looks like a hack.


It's a bit strange, yes, and is officially undefined behavior.

Maybe they could have written it as follows (note that T here is no more a pointer, whether it is a pointer in the original code):

template <class T> inline T * qgraphicsitem_cast(const QGraphicsItem *item)
{
    return int(T::Type) == int(QGraphicsItem::Type)
        || (item && int(T::Type) == item->type()) ? static_cast<T *>(item) : 0;
}

But they may have been bitten by constness, and forced to write 2 versions of the same function. Maybe a reason for the choice they made.