Nyaruko
Nyaruko

Reputation: 4479

Difference between template structure creation in C++

What is the difference between

#define Q_DECLARE_METATYPE(TYPE)                                        \
    template <>                                                         \
    struct QMetaTypeId< TYPE >                                          \
    {                                                                   \
       ...                                                              \
    };                                                                  \

and

#define Q_DECLARE_METATYPE(TYPE)                                        \
    template <TYPE>                                                     \
    struct QMetaTypeId                                                  \
    {                                                                   \
       ...                                                              \
    };                                                                  \

?

Upvotes: 0

Views: 84

Answers (2)

Nikita
Nikita

Reputation: 6427

First is explicit template specialization. Second is template definition.

Quote from the documentation:

Explicit specialization can only appear at namespace scope, in the same namespace as the primary template (or in the nearest enclosing namespace if the primary is a member template), and it has to appear after the non-specialized template declaration.

Upvotes: 1

TartanLlama
TartanLlama

Reputation: 65620

The second one defines a template class called QMetaTypeId with the template parameters provided for TYPE. Once this has been declared, specializations of QMetaTypeId can be defined for different template arguments.

The first one defines a specialization for the QMetaTypeId template class for when the template arguments are TYPE. It assumes that a template class already exists which can me specialized.

An example of each:

Q_DECLARE_METATYPE2(typename T) //primary template
Q_DECLARE_METATYPE1(int) //specialization for int

QMetaType<int> a; //uses the specialization
QMetaType<float> b; //uses the primary template

The second version seems very odd, whereas the first version might be used to make it easy for users of a library to declare specializations of a library template class for their own types.

Upvotes: 1

Related Questions