fork download
  1. #include <iostream>
  2. #include <cstdarg>
  3. #include <boost/type_traits.hpp>
  4.  
  5. using namespace std;
  6.  
  7. // for pod
  8. template<typename Type>
  9. Type sum(size_t n, ...) {
  10. typedef typename boost::promote<Type>::type PromotedType;
  11. va_list pa;
  12. Type sum = static_cast<PromotedType>(0);
  13. va_start(pa, n);
  14. while(n--)
  15. sum += va_arg(pa, PromotedType);
  16. va_end(pa);
  17. return static_cast<Type>(sum);
  18. }
  19.  
  20. int main() {
  21. cout << "correct:" << sum<unsigned> (2, 1, 2) << endl;
  22. cout << "error :" << sum<int> (2, 1.0, 2.0) << endl;
  23. cout << "correct:" << sum<double> (2, 1.0, 2.0) << endl;
  24. cout << "error :" << sum<float> (2, 1.0f, 2.0f) << endl;
  25. return 0;
  26. }
  27.  
Success #stdin #stdout 0.01s 2724KB
stdin
Standard input is empty
stdout
correct:3
error  :1072693248
correct:3
error  :3