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];
};
1

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.