How to initialize an array using the <typename T> C ++ template

Usually, if I, for example, have one string array[10], I can initialize all the spots in the array, for example:

for(int i = 0; i < 10; i++)
    array[i] = "";

or if it is an array with pointers, I write array[i] = nullptrinstead, but how to initialize when the type is more general, for example T array[10]?

+4
source share
3 answers

If initializing the value is all you need, you can initialize all elements of the array with empty brackets:

T array[10]{};
//         ^^

Or:

T array[10] = {};

Initialization of values ​​results in a zero or zero value for scalars; a value initializes each element for aggregates and calls the default constructor for non-aggregate class types.

( , T{}, - .)

+8

, , ,

template<typename T, std::size_t N>
void initialize(T (&arr)[N], const T& value = T())
{
    for(auto& e : arr)
        e = value;
}

, , .

+4

- , :

#include <iostream>
#include <string>
#include <cassert>

template <typename T>
struct A {
  // value-initialize `array` which value-initializes all elements of `array`.
  A() : array() {}
  T array[10];
};

int main() {
    A<int> ints;

    for(auto e: ints.array) {
        assert(e == 0);
    }

    A<std::string> strings;

    for(auto e: strings.array) {
        assert(e.empty());
    }

    A<int*> int_ptrs;

    for(auto e: int_ptrs.array) {
        assert(e == nullptr);
    }

    // etc.
}
+3

All Articles