Reputation: 720
i made a template class Array : here is the necessary code :
#ifndef ARRAY_H
#define ARRAY_H
#include <iostream>
#include <cstdarg>
template< typename T >
class Array
{
public:
Array(size_t length = 0, ...);
~Array();
private:
T *m_values;
size_t m_len;
};
template< typename T>
Array< T >::Array(size_t len, ...) : m_values(0), m_len(len)
{
if(len != 0)
{
m_values = new T[len];
va_list ap;
va_start(ap, len);
for(size_t i(0); i < len; i++)
m_values[i] = va_arg(ap, T);
va_end(ap);
}
else
m_values = NULL;
}
template< typename T >
Array< T >::~Array()
{
delete[] m_values;
}
#endif // ARRAY_H
and this is my main
int main()
{
Array<float> a;
return 0;
}
when i compile i get a warning "float is promoted to double when passed through (...) so that means the problem source is the constructor that takes an unknown number of arguments. why does the compiler promote the float to double, is there a way to solve it or i have to specialize the class for the float version, and how can i know if the compiler will also change other types ...
Upvotes: 4
Views: 1627
Reputation: 42929
When a function with a variable-length argument list is called, the variable arguments are passed using C's old default argument promotions. These say that types char
and short
int
are automatically promoted to int
, and type float
is automatically promoted to double
.
Therefore, varargs functions must never receive arguments of type char
, short int
, or float
.
Upvotes: 6