简体   繁体   English

使用默认成员初始值设定项初始化std :: array的元素

[英]Zero-initializing elements of a std::array with a default member initializer

Suppose I have a class template like this: 假设我有一个这样的类模板:

template<typename T, size_t N>
struct S {
   std::array<T,N> a;
};

Is there a default member initializer I can place on a , 是否有一个默认的成员初始化我可以放置a

template<typename T, size_t N>
struct S {
   std::array<T,N> a = ???;
};

such that no matter what T is, the elements of a will always be initialized (never have indeterminant value)? 这样,无论什么T是,的元素a总是会被初始化(永远不会有超静定值)? Ie, even if T is a primitive type like int . 即,即使T是像int这样的原始类型。

This: 这个:

template<typename T, size_t N>
struct S {
   std::array<T,N> a = {};
};

That will recursively copy-initialize each element from {} . 这将以递归方式{}复制初始化每个元素 For int , that will zero-initialize. 对于int ,这将零初始化。 Of course, someone can always write: 当然,有人总能写:

struct A {
    A() {}
    int i;
};

which would prevent i from being initialized. 这将阻止i被初始化。 But that's on them. 但那就是他们。

std::array is an aggregate type. std::array是一种聚合类型。 You can aggregate initialize it with empty braces {} and that will initialize accordingly the elements of the internal array of T that std::array holds. 您可以使用空括号{}聚合初始化它,并相应地初始化std::array包含的T的内部数组的元素。

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

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