How to initialize std::array<T, n> elegantly if T is not default constructible?

How do I initialize std::array<T, n> if T is not default constructible?

I know it's possible to initialize it like that:

T t{args};
std::array<T, 5> a{t, t, t, t, t};

But n for me is template parameter:

template<typename T, int N>
void f(T value)
{
    std::array<T, N> items = ??? 
}

And even if it wasn't template, it's quite ugly to repeat value by hand if n is too large.


Solution 1:

Given N, you could generate a sequence-type calledseq<0,1,2,3,...N-1> using a generator called genseq_t<>, then do this:

template<typename T, int N>
void f(T value)
{
     //genseq_t<N> is seq<0,1,...N-1>
     std::array<T, N> items = repeat(value, genseq_t<N>{});
}

where repeat is defined as:

template<typename T, int...N>
auto repeat(T value, seq<N...>) -> std::array<T, sizeof...(N)> 
{
   //unpack N, repeating `value` sizeof...(N) times
   //note that (X, value) evaluates to value
   return {(N, value)...}; 
}

And the rest is defined as:

template<int ... N>
struct seq
{
   using type = seq<N...>;

   static const std::size_t size = sizeof ... (N);

   template<int I>
   struct push_back : seq<N..., I> {};
};

template<int N>
struct genseq : genseq<N-1>::type::template push_back<N-1> {};

template<>
struct genseq<0> : seq<> {};

template<int N>
using genseq_t = typename genseq<N>::type;

Online demo

Hope that helps.

Solution 2:

Sadly the existing answers here don't work for non-copyable types. So I took @Nawaz answer and modified it:

#include <utility>
#include <array>


template<typename T, size_t...Ix, typename... Args>
std::array<T, sizeof...(Ix)> repeat(std::index_sequence<Ix...>, Args &&... args) {
   return {{((void)Ix, T(args...))...}};
}

template<typename T, size_t N>
class initialized_array: public std::array<T, N> {
public:
    template<typename... Args>
    initialized_array(Args &&... args)
        : std::array<T, N>(repeat<T>(std::make_index_sequence<N>(), std::forward<Args>(args)...)) {}
};

Note that this is an std::array subclass so that one can easily write

class A { 
    A(int, char) {}
}

...

class C {
    initialized_array<A, 5> data;

    ...

    C(): data(1, 'a') {}
}

Without repeating the type and size. Of course, this way can also be implemented as a function initialize_array.