简体   繁体   English

如何在使用模板时初始化数组 <typename T> C ++

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

Normally if I for example have string array[10] I can initialize all spots in the array like: 通常,如果我有例如string array[10]我可以初始化数组中的所有点,如:

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] ? 或者如果它是一个带指针的数组,我会编写array[i] = nullptr ,但是当类型更像T array[10]时,我该如何初始化?

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.) (如果要使用T{}以外的值初始化数组元素,则需要更复杂和特定的内容。)

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. 现在你可以调用它,而不是传递一个值,并使用默认值初始化数组,或者你可以指定一个值,数组将用该值初始化。

If your goal is to call the default constructor on all elements of the array, you can use value-initialization: 如果您的目标是在数组的所有元素上调用默认构造函数,则可以使用值初始化:

#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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM