2

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88
user877329
  • 6,717
  • 8
  • 46
  • 88

1 Answers1

4

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>{});
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 1
    Kudos, but, ehm, I know that readability is subjective, but I'd freak out if I had to review this. Do you consider the intent of this code explicit? – MatG Aug 04 '23 at 21:08
  • @MatG So would I. – Paul Sanders Aug 04 '23 at 21:47
  • 1
    @MatG It is common pattern for stuff like that. If you're unfamiliar with template metaprogramming you won't be able to read any generic code anyway(no matter how explicit it is). You can have a look at Haskel code, it is pure alien language until you learn it in details. – Dmitry Aug 05 '23 at 07:08
  • @MatG See the explanation here: https://gcc.godbolt.org/z/bGe3M7KG5 – JeJo Aug 05 '23 at 07:56
  • 1
    @MatG Would it help you to recognise the pattern, if made a bit more [generic](https://gcc.godbolt.org/z/fq13YGqzP)? I don't know how common it is in the wild, but you can find examples of its use in some Q&A here and other cpp resources available online. – Bob__ Aug 05 '23 at 10:16