让我们阅读源代码(我使用的是 Qt 4.8)。
qlist.h:
struct Node {
void *v;
#if defined(Q_CC_BOR)
Q_INLINE_TEMPLATE T &t();
#else
Q_INLINE_TEMPLATE T &t()
{ return *reinterpret_cast<T*>(QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic
? v : this); }
#endif
};
QList 使用QTypeInfo 来确定类型属性。 QTypeInfo 分别为各种类型声明。在 qglobal.h 中:
未知类型的默认声明:
template <typename T>
class QTypeInfo
{
public:
enum {
isPointer = false,
isComplex = true,
isStatic = true,
isLarge = (sizeof(T)>sizeof(void*)),
isDummy = false
};
};
指针声明:
template <typename T>
class QTypeInfo<T*>
{
public:
enum {
isPointer = true,
isComplex = false,
isStatic = false,
isLarge = false,
isDummy = false
};
};
用于方便类型信息声明的宏:
#define Q_DECLARE_TYPEINFO_BODY(TYPE, FLAGS) \
class QTypeInfo<TYPE > \
{ \
public: \
enum { \
isComplex = (((FLAGS) & Q_PRIMITIVE_TYPE) == 0), \
isStatic = (((FLAGS) & (Q_MOVABLE_TYPE | Q_PRIMITIVE_TYPE)) == 0), \
isLarge = (sizeof(TYPE)>sizeof(void*)), \
isPointer = false, \
isDummy = (((FLAGS) & Q_DUMMY_TYPE) != 0) \
}; \
static inline const char *name() { return #TYPE; } \
}
#define Q_DECLARE_TYPEINFO(TYPE, FLAGS) \
template<> \
Q_DECLARE_TYPEINFO_BODY(TYPE, FLAGS)
原始类型声明:
Q_DECLARE_TYPEINFO(bool, Q_PRIMITIVE_TYPE);
Q_DECLARE_TYPEINFO(char, Q_PRIMITIVE_TYPE); /* ... */
它也是为特定的 Qt 类型定义的,例如在 qurl.h:
Q_DECLARE_TYPEINFO(QUrl, Q_MOVABLE_TYPE);
或者在qhash.h中:
Q_DECLARE_TYPEINFO(QHashDummyValue, Q_MOVABLE_TYPE | Q_DUMMY_TYPE);
当QList 使用QTypeInfo<T> 时,编译器会选择当前最接近的QTypeInfo 定义。