I
I
Insolent Muzzle2020-06-08 19:31:54
OOP
Insolent Muzzle, 2020-06-08 19:31:54

Why is the number of elements in the array structure written in the same place as the data type?

In C++, when declaring a template class, they write: If there is a constructor with parameters, then: But in the dynamic array data structure, they write: Where int is the data dip, and 7 is the number of elements. So why is 7 spelled there? And how can it be done the same way?
myClass<int> object;
myClass<int> object(3);
array<int, 7> myArray;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2020-06-08
@pluffie

This is called Non Type Template Parameter (NTTP). You can only pass constants there (if you don't try to blow your brains out). You can declare such a template like this:

template <size_t size>
struct Array {
    MyClass data[size];
};

Array<5> a;
a.data[2] = ...;

I'll leave the definition of the methods as an exercise for the reader.
std::array has two template parameters: a type and a constant, so it applies not only to MyClass, but to any other types.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question