Search code examples
c++c++17stdarray

How to convert std::array<double, 100> to std::array<float, 100> ? (avoiding obvious boilerplate implementation)


Suppose I have an std::array of doubles and would like it converted to floats:

std::array<double, 100> d_array{1,2,3};
std::array<float, 100> f_array; <--convert it from d_array;

If using a std::vector it is extremely simple:

std::vector<float> f_array(d_array.begin(), d_array.end());

I know std::array is an aggreate type, so it seems I have to do some manual jumps on the spot in order to copy convert it to an array or is there a convenient way to do this ?

I consider std::copy boilerplate as well eg.:

std::array<float, 100> f_array;
std::copy(d_array.begin(), d_array.end(), f_array.begin());

This is not simpler than the vector version and cannot be :

const std::array<float, 100> f_array;

Thus ruining otherwise const-correct'ed code.


Solution

  • While Miles Budnek's answer solves OP's problem, it may fail if the array is too big (note that you are asking the compiler to generate and execute a function with N parameters). See e.g. this example.

    An alternative could be to use a simple for loop, which, since C++14, is allowed inside constexpr functions.

    template< class R, class T, size_t N>
    constexpr std::array<R, N> array_copy(std::array<T, N> const &src)
    {
        std::array<R, N> tmp {};
        for (size_t i{}; i < N; ++i)
            tmp[i] = static_cast<R>(src[i]);
        return tmp;
    }
    

    Live HERE.