Erindy
Erindy

Reputation: 155

Traversing Template Parameter Packs, what is the role of the specialization which takes no argument?

I have the following piece of code:

template<typename... Types>
struct TupleSize;

template<typename Head, typename... Tail>
struct TupleSize<Head, Tail...>
{
    static const size_t value = sizeof(Head) + TupleSize<Tail...>::value;
};

template<> struct TupleSize<>
{
    static const size_t value = 0;
};


int main()
{
    //consuming_templates();
    //template_functions();
    //variadic();
    TupleSize<>::value;
    TupleSize<int, double, char>::value;
    getchar();
    return 0;
}

I do not understand what is the role of:

template<typename... Types>
struct TupleSize;

Where is actually being used because I know that TupleSize<>::value; returns 0 and the other piece of code:

template<typename Head, typename... Tail>
struct TupleSize<Head, Tail...>
{
    static const size_t value = sizeof(Head) + TupleSize<Tail...>::value;
};

is used to split the parameter pack and recursively calculate the value.

Is this just a declaration, if yes why, if not where is it being used. The only scenario I can immagine is when the recursion hits its final value i.e becomes TupleSize. But I do not understand how can a template struct type exists like this, shouldn't it be:

template<typename... Types>
struct TupleSize<typename... Types>; 

Upvotes: 2

Views: 78

Answers (1)

songyuanyao
songyuanyao

Reputation: 172964

Is this just a declaration, if yes why, if not where is it being used.

It's the declaration of the primary template, taking arbitrary template parameters. It has two specializations; the primary template is never used, because when specify 1 template argument or several template arguments more than 1, the 1st specialization is selected; if specify no template argument (empty) the 2nd specialization is selected.

Upvotes: 3

Related Questions