I want to calculate the sum of any number of arguments given to function sum
. Assuming that integers given to the function will satisfy operator+
.
If I comment out the function sum()
(the one having no arguments), the code does not compile. And if I uncomment it, the code does compile and run, but never hits the function sum()
.
I can't seem to understand that why do we need to have sum()
function at all as I am using condition on sizeof...(Args)
Will really appreciate it if someone can help me understand this?
/*
int sum()
{
std::cout << "Sum with 0 Args" << std::endl;
return 0;
}
*/
template <typename T, typename...Args>
T sum(T first, Args...args)
{
// std::cout << sizeof...(Args) << std::endl;
if (sizeof...(Args) != 0)
{
return first + sum(args...);
}
else
{
std::cout << "Found 0 args" << std::endl;
return first;
}
}
int main()
{
std::cout << sum(1, 2, 3) << std::endl;
std::cout << sum(1.2, 3.5) << std::endl;
return 0;
}
Once I uncomment function sum(), I get below output -
Found 0 args
6
Found 0 args
4.7
Basically sum()
never get called which is expected, but then why do we need it in the first place?