我使用的std ::阵列<为size_t,N> (N是一个固定的模板变量)。
I am using std::array<size_t, N> (N is a fixed template-variable).
#include<array> template<size_t N> struct A{ size_t function(std::array<size_t, N> arr){ return arr[N-1];} // just an example } int main(){ A<5> a; a.function({{1,2,3,4,5}})); }和它工作正常。问题是,这一等code被悄悄允许的:
And it works fine. The problem is that this other code is silently allowed:
A.function({{1,2,3}}));也就是说,即使错过了元素阵列以某种方式初始化,即使它被很好地定义(初始化为零如剩余的元素,我不知道)这是错误的一个可能来源。
That is, even with missed elements the array is initialized somehow, even if it is well defined (e.g. remaining elements initialized to zero, I am not sure) this is a possible source of errors.
有没有办法强制执行额外的要素是什么?例如初始化通过产生一个编译器错误或警告。
Is there a way to enforce the initialization of the extra elements? E.g. by generating a compiler error or a warning.
这是我考虑的一个选择是使用 initializer_list
One option that I contemplated is to use initializer_list
size_t function2(std::initializer_list<size_t> il){ assert(il.size() == N); ...}的问题是,这产生最好的运行时错误,并在每呼叫的支票。我想preFER编译器错误/警告。
The problem is that this generated a runtime error at best and a check in every call. I would prefer a compiler error/warning.
我没有那么多通过的默认初始化的std ::阵列&LT困扰{} 而是通过的不完整的的初始化。 (也许没有什么能对此做,因为这是从 T [N] 静态数组的行为继承。)
I am not so much bothered by the default initialization of std::array<>{} but by the incomplete initialization. (Maybe there is nothing it can be done about it, since this is inherited from the behavior of T[N] static array.)
我试着用铛3.5 和 GCC 5 。
推荐答案答案很简单:你不能
当初始化时的std ::阵列与列表,它是做一个集合初始化,它解释 rel=\"nofollow\">当列表大小小于成员数:
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:
- 如果初始化子句的数目少于成员或初始化列表的数目是完全空的,剩余的成员按其撑 - 或等于初始化初始化,如果在类定义提供,并以其他方式(由于C + +14)由空列表,它执行值初始化。如果引用类型的成员是这些剩下的成员之一,该计划是非法的构造(引用不能值初始化)
这只不过是一个法律和可接受的行为,以提供比大小列表少,所以编译器不会抱怨什么。您code:
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}}));相当于:
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).
更多推荐
有没有办法强制执行的std完全初始化数组::
发布评论