Mr.Anubis
Mr.Anubis

Reputation: 5312

Variadic templates mystery

Here is the code that works fine :

template<typename... Args> struct count;

template<>
struct count<> {
static const int value = 0;
};

template<typename T, typename... Args>
struct count<T, Args...> {
static const int value = 1 + count<Args...>::value;
};

now i was wondering why we need to partial specialize the count class template?

Can we do something like :

template< typename... args> struct dd; // edited according to answer but now getting error redeclared with 2 template parameters which is point below with mark %%

template<>
struct dd<>{
static const int value = 0;
};

template<typename T, typename... args> //%%
struct dd{
static const int value= 1+ dd<args...>::value;
};

but this doesn't works but why?

Any help is very appreciated :)

Edit : edited the solution according to answer.

Upvotes: 3

Views: 1408

Answers (2)

Cat Plus Plus
Cat Plus Plus

Reputation: 129754

With template <typename T, typename... Args> you can't create a specialisation that omits T (i.e. dd<>) — the pack can be empty, but T can't. So you declare the template as one that takes only a pack, specialise for empty pack to stop recursion, and partially specialise for <T, Args...> to unpack one type and create a new pack with (n - 1) types.

As for the edit: you can't define another template with different arguments but the same name, you have to specialise the already existing one.

Upvotes: 2

UncleBens
UncleBens

Reputation: 41331

template<>
struct dd<> {
static const int value = 0;
};

is not a specialization of

template< typename T,typename... args> struct dd;

which says dd will always require at least one parameter.


Sidenote, there already is a built-in way to get the number of variadic template parameters and the count struct could be implemented as

template <class ...args>
struct count
{
    static const int value = sizeof...(args);
};

Upvotes: 5

Related Questions