Why do I have to assign a size for a std::array, when a plain array doesn't have to be?

552 Views Asked by At
std::array<int, 3> foo = {1,2,3};
int bar[] = {1,2,3}; // the size is 3

For a plain array I don't have to assign the size. But I have to assign the size for std::array. Why?

1

There are 1 best solutions below

0
On BEST ANSWER

Arrays in C++ have a separate set of rules from other types. If the size is not specified, the size can be deduced from the number of arguments provided in the initalizer.

std::array on the other hand is a class template, so you need to specify all the arguments when instantiating an object of that type.

From C++17, this requirement has been relaxed, since the compiler will now do class-template-argument-deduction. So now you can omit the type and the size, and the compiler will deduce both of them from the type and number of arguments in the initializer:

std::array foo = {1,2,3};  // ok, int and 3