This is a good answer already, however, they passed arbitrary numbers of arguments as the parameters when I tried to do the same with arguments as typename (don't know the exact word) like this for example:
int sum=0;
int func()
{
return sum;
}
template <int first, int ... rest>
int func()
{
sum += first;
return func(rest...); //Error C2660 'func': function does not take 4 arguments
/*
return func<rest...>(); this also doesn't work: Error 'int func(void)': could not deduce template argument for 'first' and 'func': no matching overloaded function found
*/
}
int main()
{
cout << func<1,2,3,4,5>();
}
Why there's an error there? Are there any possible fixes? Also, I'm required to pass the argument as typenames, not parameters.
First of all, the "base" function also needs to be a template.
Then to differentiate the two templates, the parameter-pack template needs to take at least two template arguments.
And lastly, you can solve this without the global sum
variable, but using the addition in the return
statement.
Putting it all together:
template <int first>
int func()
{
return first;
}
template <int first, int second, int ...rest>
int func()
{
return first + func<second, rest...>();
}