Not really, since when a raw array type is initialized with fewer than its count of expressions, objects get default-initialized.
But one thing you could do would be to create your own array-like class template:
#include <cstddef>
#include <type_traits>
#include <initializer_list>
#include <utility>
#include <iterator>
template <std::size_t N>
class MyObjectArray
{
public:
using array_type = MyObject[N];
template <typename T, typename Enable =
std::enable_if_t<std::is_convertible_v<T, int>>>
MyObjectArray(T (&arr)[N]);
template <typename T = int, typename Enable =
std::enable_if_t<std::is_convertible_v<T, int>>>
MyObjectArray(std::initializer_list<T> il);
template <typename InputIter, typename Enable =
std::enable_if_t<std::is_convertible_v<
typename std::iterator_traits<InputIter>::reference, int>>>
MyObjectArray(InputIter start, InputIter end);
operator array_type& () noexcept { return m_array; }
operator const array_type& () const noexcept { return m_array; }
private:
template <std::size_t... I, typename InputIter>
MyObjectArray(std::index_sequence<I...>, InputIter iter)
: m_array{ (static_cast<void>(I), *iter++) ... } {}
static std::make_index_sequence<N> check_count(std::size_t n) {
if (n != N)
throw std::invalid_argument(
"Incorrect number of elements initializing MyObjectArray");
// Or if exceptions not supported, some other error reporting
// mechanism and abort.
return {};
}
MyObject m_array[N];
};
template <std::size_t N>
template <typename T, typename Enable>
MyObjectArray<N>::MyObjectArray(T (&arr)[N])
: MyObjectArray(std::make_index_sequence<N>{}, arr) {}
template <std::size_t N>
template <typename T, typename Enable>
MyObjectArray<N>::MyObjectArray(std::initializer_list<T> il)
: MyObjectArray(check_count(il.size()), il.begin()) {}
template <std::size_t N>
template <typename InputIter, typename Enable>
MyObjectArray<N>::MyObjectArray(InputIter start, InputIter end)
: MyObjectArray(check_count(std::distance(start, end)), start) {}
This can be used like:
int main()
{
const int myInts[5] = {1, 2, 3, 4, 5};
MyObjectArray obj_array(myInts);
MyObjectArray<5> a2 = {3, 4, 5, 6, 7};
}
See the working code on coliru.
std::array(orboost::array, or your own variant). It doesn't allocate anything dynamically. Do you require exactly the initialization syntax that you are asking for?std::array's? Also, what language standard can you use (03,11,14,17)?std::arrayalso not allowed. The (highly proprietary) compiler allows a subset of C++11, but no dynamic memory, no recursion, no STL datatypes, no transcendental functions, etc.