Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

Normally if I for example have string array[10] I can initialize all spots in the array like:

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

or if it is an array with pointers I write array[i] = nullptr instead, but how do I initialize when the type is more general like T array[10]?

like image 406
Mallom Avatar asked Dec 06 '22 18:12

Mallom


2 Answers

If value-initialization is all you need, then you can value-initialize all array members with empty braces:

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

Or:

T array[10] = {};

Value-initialization produces the zero or null value for scalars, value-initializes each member for aggregates, and calls the default constructor for non-aggregate class types.

(If you want to initialize your array elements with values other than T{}, then you need something more complex and specific.)

like image 141
Kerrek SB Avatar answered Mar 05 '23 20:03

Kerrek SB


Well you could do like the standard does and use an initialization function in the form of

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

Now you can call this and not pass a value and the array with be initialized with default value or you can specify a value and the array will be initialized with that value.

like image 30
NathanOliver Avatar answered Mar 05 '23 19:03

NathanOliver