I am trying to write a function which accepts multiple arguments of different data types and return the sum of numbers. It should be able to decide what data type to be used for sum. For e.g. if I write add(3,1,2,3) it should return sum as an int. However, if I write add(3,1,2.5,3.25) it should return sum as a double.
I tried using template, but giving compile time error. Here is the function
template <typename T>
T add(int n, ...)
{
T sum = 0;
va_list vl;
va_start(vl,n);
for(int i=0;i<n;i++)
{
sum += va_arg(vl,T);
}
va_end(vl);
return sum;
}
int main()
{
std::cout<<add(3,1,2,3);
return 0;
}
Compile Error: no matching function for call to 'add(int, int, int, int)'. I think error is coming because I passed in va_arg T, but i don't know what else to pass to keep it generalised.