I am trying to write a function that takes several arguments of different data types and returns the sum of numbers. He should be able to decide what type of data will be used for the amount. E.g. if I write add (3,1,2,3), it should return the amount as int. However, if I write add (3,1,2,5,3,25), it should return the amount as double.
I tried using the template, but gave a 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; }
Compilation error: there is no corresponding function to call 'add (int, int, int, int)'. I think the error is coming because I went to va_arg T, but I donβt know what else to pass so that it is generalized.
source share