why does c++11 std::array using template to initialize the max_size not constructor?

c++, c++11

Solution

Because if it didn't, it wouldn't be able to be what it is.

`std::array` is an array. Not a dynamically-sized array. Not a runtime-sized array. It is an array, much like `int arr[5]`.

C++ is a statically typed language, which means that C++ types must have a compile-time defined size. `arr` in the above example has a size; if you do `sizeof(arr)`, you will get `sizeof(int) * 5`. `sizeof(std::array<int, 5>)` has a size as well, which is defined by the number of elements in it. Therefore, the size must be a compile-time defined quantity, since it factors into the compile-time defined size.

The differences between `std::array` and regular arrays are:

- Arrays will decay into pointers implicitly. `std::array` does not; you need to explicitly call a function to do that.

- Arrays are language arrays; `std::array`, to the language, is a struct which contains an array.

if I have a lot of arrays just differs in sizes, there'll be a lot of code to be generated.

Yes, you might. Then again... is this a serious concern? Have you really looked at a `std::array` implementation?

There's not much there. `T operator[](int index) { return elems[index]; }` I don't think getting a couple hundred instantiations of that function is going to be a problem. Same goes for `begin`, `size`, `empty`, etc. You're talking about code that will almost certainly be inlined.

Problem

c++11 uses template to define the max_size of the array (eg. `std::array<int, 5> a1;`) but not constructor. (eg. `std::array<int>(5) a1;`) Since template is going to generate code for the class, and if I have a lot of arrays just differs in sizes, there'll be a lot of code to be generated. (1. It may cause increase in compile time. 2. It may cause the expension of the code part of the executable file.)

Original source