user877329
user877329

Reputation: 6220

How to create an array of N floats values with fold expression?

Suppose the following function

template<size_t N>
constexpr std::array<float, N> make_ones()
{
    std::array<float, N> ret{};
    for (size_t k = 0; k != N; ++k)
    {
        ret[k] = 1.0f;
    }
    return ret;
}

Is it possible to write that with a fold expression? The problem is that I do not have a pack to expand.

Upvotes: 2

Views: 336

Answers (1)

JeJo
JeJo

Reputation: 32952

Is it possible to write that with a fold expression?

Not with fold expression but pack expansion as well as with index sequence, in you could do:

template <size_t N>
constexpr std::array<float, N> make_ones()
{
    return []<size_t... Is>(std::index_sequence<Is...>) {
        return std::array<float, sizeof...(Is)>{( static_cast<void>(Is), 1.0f)...};
    }(std::make_index_sequence<N>{});
}

See live demo in godbolt.org


For compilers that doesn't support C++20 or later, you might do

template <size_t... Is>
constexpr std::array<float, sizeof...(Is)> make_ones_impl(std::index_sequence<Is...>)
{
    return std::array<float, sizeof...(Is)>{(static_cast<void>(Is), 1.0f)...};
}

template<size_t N>
constexpr std::array<float, N> make_ones()
{
    return make_ones_impl(std::make_index_sequence<N>{});
}

Upvotes: 4

Related Questions