Can C++ raise an error when std array initialization is too small?
You can use std::make_array
or something like it to cause the types to differ
std::array<int, 6> = std::make_array(4,3,2);
gives this error in gcc:
<source>:30:53: error: conversion from 'array<[...],3>' to non-scalar type 'array<[...],6>' requested
You can create your own layer of abstraction that complains when you don't pass the exact same number of arguments for initialization.
template <std::size_t N, class ...Args>
auto createArray(Args&&... values)
{
static_assert(sizeof...(values) == N);
using First = std::tuple_element_t<0, std::tuple<Args...>>;
return std::array<First, N>{values...};
}
To be invoked as
auto ok = createArray<6>(4, 3, 2, 1, 0, -1);
auto notOk = createArray<6>(4, 3, 2};
Instead of writing your own createArray method you can use the https://en.cppreference.com/w/cpp/experimental/make_array
if your compiler supports it.
#include <experimental/array>
int main()
{
std::array<int,5> arr1= std::experimental::make_array(1, 2, 3, 4, 5); // ok
std::array<int,3> arr2= std::experimental::make_array(1, 2, 3, 4, 5); // fails
std::array<int,6> arr3= std::experimental::make_array(1, 2, 3, 4, 5); // fails
}
But everybody can directly init the array via constructor. So there is no guarantee for your code base if you don't check ( automatically ) against some coding guidelines.