Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why float is promoted to double when using template and stdarg function

Tags:

c++

templates

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 ...

like image 818
zeralight Avatar asked Oct 26 '25 05:10

zeralight


1 Answers

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.

like image 107
101010 Avatar answered Oct 27 '25 21:10

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!