views:

51

answers:

1

I have a variadic template function:

template<typename T, typename ArgType>
vector<T>
createVector(const int count, ...)
{
  vector<T> values;
  va_list vl;
  va_start(vl, count);
  for (int i=0; i < count; ++i)
  {
    T value = static_cast<T>(va_arg(vl, ArgType));
    values.push_back(value);
  }
  va_end(vl);
  return values;
}

This works for some (to me, strange) configurations of T and ArgType, but not the way I expect:

// v1 = [0.0, 1.875, 0.0]
vector<float> v1 = createVector<float, float>(3, 1.0f, 2.0f, 3.0f);
// v2 = [0.0, 1.875, 0.0]
vector<float> v2 = createVector<float, float>(3, 1.0, 2.0, 3.0);
// v3 = [1.0, 2.0, 3.0]
vector<float> v3 = createVector<float, double>(3, 1.0, 2.0, 3.0);
// v4 = [1.0, 2.0, 3.0]
vector<float> v4 = createVector<float, double>(3, 1.0f, 2.0f, 3.0f);    
// v5 = [1.0, 2.0, 3.0]
vector<double> v5 = createVector<double, double>(3, 1.0, 2.0f, 3.0);  

Why does this work when ArgType is double (even when passing floats), but not when it's float?

+6  A: 

Floating point values are passed as doubles when passed to variadic functions, just as integers small than int are passed as int.

Anthony Williams
+1 Interesting, I never knew that.
fingerprint211b
Are floats also passed as doubles?
James Curran
@James: yes, floats are passed as doubles.
Anthony Williams
Is there any good reason for this?
larsm
It's the way C does it (and always has).
Anthony Williams