Is there a way to enforce full initialization of std::array

后端 未结 3 1597
耶瑟儿~
耶瑟儿~ 2021-01-02 05:18

I am using std::array (N is a fixed template-variable).

#include
template
struct A{
   size_t fun         


        
3条回答
  •  -上瘾入骨i
    2021-01-02 05:53

    Simple answer: You cannot.

    When initializing std::array with a list, it is doing an aggregate initialization, and it is explained here when the list size is less than the number of member:

    • If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are initialized by their brace-or-equal initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, which performs value-initialization. If a member of a reference type is one of these remaining members, the program is ill-formed (references cannot be value-initialized)

    It is simply a legal and acceptable behavior to provide less than the size list, so compiler will not complain anything. Your code:

    A<5> a;
    a.function({{1,2,3}}));
    

    is equivalent to:

    A<5> a;
    a.function({{1,2,3,0,0}}));
    

    to compiler. Your best bet is runtime error (which may not be as you wished).

提交回复
热议问题