Consider the following (C++20) function (from the solution to this StackOverflow question):
template<std::size_t N, class T>
constexpr auto array_repeat(T&& x)
{
auto deref = []<std::size_t> (T x) { return x; };
auto impl = [&]<std::size_t... Indices>(T&& x, std::index_sequence<Indices...>)
{
return std::array{deref.template operator()<Indices>(x)...};
};
return impl(std::forward<T>(x), std::make_index_sequence<N>());
}
What this function does is take the argument x and repeat it N times in an std::array constructor.
Now, this works, but - I don't like the amount of hoops I have to jump through, I don't like having to nest two helper functions/lambdas, I don't like to use std::index_sequence's, and I certainly don't like to have to say "template operator" :-(
Is it possible to use fold expressions to generate the N repetitions more elegantly, or tersely, or both? Also, if you have other ideas for simplifying this code, that would be appreciated. I'm mostly interested in C++20 here, but C++23 or C++26 are also fine.
Note: You may not assume T is default-constructible.
template<std::size_t N, typename T> auto array_repeat(T const& t) { return std::apply([&](auto... e) {return std::array{(e, t)...};}, std::array<int, N>{});}\$\endgroup\$Tis default-constructible, which is not necessarily the case. \$\endgroup\$Tcan be non default-constructible. Check this out godbolt.org/z/1YqPv6s87 \$\endgroup\$