A member variable of type std :: array <T,?>

How to declare and set a member variable for an AClass class that has type std::array<T, ?> (With size undefined)? The actual std::array must be created in the constructor, where the size of the array is a constructor parameter.

In pseudo-C ++ code:

 template <typename T> class AClass { protected: std::array<T, ?>* array; public: AClass(int n) { this->array = new std::array<T, n>; } } 

What will the code look like?

+7
source share
4 answers

Do not use std::array for this, use std::vector . The size of std::array should be a compile time constant. If you want to pass it in the constructor, you need to use std::vector .

+14
source

The actual std::array must be created in the constructor, where the size of the array is the constructor parameter.

The size of the std::array file must be known at compile time, which is not the case in your case.

For this you need to use std::vector .

+9
source

Disable the use of std::vector , where the size is really determined at run time, you can also specify the size at compile time (for example, the maximum possible value depending on your problem) and "distribute" the template parameter to the clients of your class, i.e.

 template <typename T, std::size_t n> class AClass { protected: std::array<T, n> array; public: AClass() { // nothing to do } } 

you can use it as follows:

 AClass<int, 5> myAClass; 
+4
source

You cannot have std::array with size undefined.
Use std::unique_ptr<T[]> or std::vector instead.

+2
source

All Articles