I have the following code with a variadic template copied from: https://www.youtube.com/watch?v=iWvcoIKSaoc @41:30
auto sum() { return 0; }
template<typename Head, typename... Tail>
auto sum(Head head, Tail... tail)
{
return head+sum(tail...);
}
int main() {
cout<< sum(1,2.4) << endl;
//cout<< sum("hello ", "world") << endl;
return 0;
}
I have two questions: 1. The sum() function is required here so that I can have a return value for a void passed in when processing the last variadic member - Is it possible to avoid writing this sum() function and have the same functionality?
Thank You
The trick is to never allow empty sum()
calls, and treat the sum(last)
as the last recursion:
template<typename Last>
auto sum(Last last) {
return last;
}
template<typename Head, typename Second, typename... Tail>
auto sum(Head head, Second second, Tail... tail)
{
return head + sum(second, tail...);
}
int main() {
cout<< sum(1,2.4) << endl;
cout<< sum("hello ", "world") << endl;
return 0;
}