65,186
社区成员




#include <iostream>
#include <cstdarg>
template <class T>
T sum(int n,T b,...)
{
va_list ap;
T temp;
va_start(ap, b);
T sum1=b;
for(int i=0;i<n-1;i++)
{
temp=va_arg(ap,T);
sum1 += temp;
}
va_end(ap);
return(sum1);
}
int main()
{
int intA = 2;
int intB = 3;
std::cout <<intA<<"+"<<intB<<"="<<sum(2, intA, intB)<<'\n';
double doubleA = 2.2;
double doubleB = 3.3;
std::cout <<doubleA<<"+"<<doubleB<<"="<<sum(2, doubleA, doubleB)<<'\n';
// 下面输出的结果是错误的!! why?
float floatA = 2.1f;
float floatB = 3.1f;
std::cout <<floatA<<"+"<<floatB<<"="<<sum(2, floatA, floatB)<<'\n';
return 0;
}
test.cpp: In function ‘T sum(int, T, ...) [with T = float]’:
test.cpp:33: instantiated from here
test.cpp:13: warning: ‘float’ is promoted to ‘double’ when passed through ‘...’
test.cpp:13: warning: (so you should pass ‘double’ not ‘float’ to ‘va_arg’)
test.cpp:13: note: if this code is reached, the program will abort