I want to calculate 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), code does not compile. And if i remove the comment block, code does compile and run but never hits the function sum().
I cant 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 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?
Aucun commentaire:
Enregistrer un commentaire