3

Is there any way to construct an array of non default constructible objects of numObjects length where numObjects is a template argument? For example...

struct NonDefaultConstructibleClass
{
    NonDefaultConstructibleClass(int){}
};

template<size_t numObjects>
struct Thing
{
    Thing() : m_Objects{{3, 3, 3, /*... numObjects times */}} {}

    NonDefaultConstructibleClass m_Objects[numObjects];
};
David
  • 27,652
  • 18
  • 89
  • 138
  • Does this answer your question? [How to initialize std::array elegantly if T is not default constructible?](https://stackoverflow.com/questions/18497122/how-to-initialize-stdarrayt-n-elegantly-if-t-is-not-default-constructible) – user202729 Feb 12 '22 at 11:13

1 Answers1

3

In the constructor of Thing, you can create a parameter pack with N elements, and forward the construction to a variadic constructor. The variadic constructor initializes the array with regular parameter expansion.

template <std::size_t N>
struct Thing
{
    NonDefaultConstructibleClass _elements[N];
    Thing() : Thing{build_indexes<N>{}} { }
    template <std::size_t... Indexes>
    Thing(indexes<Indexes...>)
        : _elements{(Indexes, 3)...}
    { }
};

indexes and build_indexes are simple helper classes. C++14 will most likely contain something similar (std::integer_sequence). In GCC you can use the following type aliases:

template <std::size_t ...Indexes>
using indexes = std::_Index_tuple<Indexes...>;

template <std::size_t N>
using build_indexes = typename std::_Build_index_tuple<N>::_type;
nosid
  • 48,932
  • 13
  • 112
  • 139
  • If the array is a `std::array` you do not even have to constructor forward: just call a helper fumction. This is useful if your compiler lacks support for forwarding ctors, or if you find the extra ctor distracting. – Yakk - Adam Nevraumont Oct 06 '13 at 12:24