std::array<T>初始化 [英] std::array<T> initialization

查看:28
本文介绍了std::array<T>初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::array<T> 本质上是包装在 struct 中的 C 样式数组.struct的初始化需要大括号,数组的初始化也需要大括号.所以我需要两对大括号:

A std::array<T> is essentially a C-style array wrapped in a struct. The initialization of structs requires braces, and the initialization of arrays requires braces as well. So I need two pairs of braces:

std::array<int, 5> a = {{1, 2, 3, 4, 5}};

但是我看到的大多数示例代码只使用了一对大括号:

But most of the example code I have seen only uses one pair of braces:

std::array<int, 5> b = {1, 2, 3, 4, 5};

为什么允许这样做,与第一种方法相比,它有什么好处或缺点?

How come this is allowed, and does it have any benefits or drawbacks compared to the first approch?

推荐答案

这样做的好处是你有...更少的输入.但缺点是只有在声明具有该形式时才允许您省略大括号.如果您不使用 =,或者如果数组是一个成员并且您使用 member{{1, 2, 3, 4, 5}} 对其进行初始化,则您不能只传递一对大括号.

The benefit is that you have ... less to type. But the drawback is that you are only allowed to leave off braces when the declaration has that form. If you leave off the =, or if the array is a member and you initialize it with member{{1, 2, 3, 4, 5}}, you cannot only pass one pair of braces.

这是因为在将大括号传递给函数时,担心可能出现重载歧义,如 f({{1, 2, 3, 4, 5}}).但这引起了一些讨论,并生成了问题报告.

This is because there were worries of possible overload ambiguities when braces are passed to functions, as in f({{1, 2, 3, 4, 5}}). But it caused some discussion and an issue report has been generated.

基本上,= { ... } 初始化总是能够省略大括号,如

Essentially, the = { ... } initialization always has been able to omit braces, as in

int a[][2] = { 1, 2, 3, 4 };

这并不新鲜.新的是你可以省略 =,但是你必须指定所有的大括号

That's not new. What is new is that you can omit the =, but then you must specify all braces

int a[][2]{ {1, 2}, {3, 4} };

这篇关于std::array&lt;T&gt;初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆