Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 388
Mr.Anubis Avatar asked Jan 01 '26 00:01

Mr.Anubis


1 Answers

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);
};
like image 117
UncleBens Avatar answered Jan 02 '26 13:01

UncleBens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!