How do I initialize std::array if T is not default constructible?
I know it\'s possible to initialize it like that:
Following will solve your issue:
#if 1 // Not in C++11, but in C++1y (with a non linear better version)
template struct index_sequence {};
template
struct make_index_sequence : make_index_sequence {};
template
struct make_index_sequence<0, Is...> : index_sequence {};
#endif
namespace detail
{
template
constexpr std::array
create_array(T value, index_sequence)
{
// cast Is to void to remove the warning: unused value
return {{(static_cast(Is), value)...}};
}
}
template
constexpr std::array create_array(const T& value)
{
return detail::create_array(value, make_index_sequence());
}
So test it:
struct NoDefaultConstructible {
constexpr NoDefaultConstructible(int i) : m_i(i) { }
int m_i;
};
int main()
{
constexpr auto ar1 = create_array<10>(NoDefaultConstructible(42));
constexpr std::array ar2 = create_array<10>(NoDefaultConstructible(42));
return 0;
}