c++ - Why is double brace required to initialize std::array of structs
问题描述
In C++17, why does this way of initializing std::array not work?
#include <array>
#include <string_view>
class myClass {
private:
struct myStruct {
const std::string_view a;
const int b;
const int c;
};
static inline constexpr std::array<myStruct, 2> myArray = {{"", 0, 0},{"", 0, 0}};
};
I thought this style was covered by the changes in CWG 1270. However, the only way I found to make it work is to do:
static inline constexpr std::array<myStruct, 2> myArray = {{{"", 0, 0},{"", 0, 0}}};
or
static inline constexpr std::array<myStruct, 2> myArray = {myStruct{"", 0, 0},myStruct{"", 0, 0}};
解决方案
让我们用一个更简单的例子来解决这个问题:
std::array<int, 3> arr{{1,2,3}};
我们首先回顾如何std::array
定义。它具有
与将 C 样式数组 T[N] 作为其唯一的非静态数据成员的结构具有相同的语义。
因此,换句话说,这std::array
是一个具有单个“非静态数据成员”的对象,它是一个 C 样式的数组。基于此,我们可以得出:
最外面的一组大括号服务器初始化
std::array
自身。最里面的一组大括号初始化这个未命名的数据成员。
换句话说,这与以下内容完全相同:
struct my_array {
int a[3];
};
my_array arr{{1,2,3}};
这就是为什么总是使用一组双外括号来初始化 a 的实例std::array
。
推荐阅读
- c# - 减小 PNG 图像的大小
- authentication - Web Authn 和 Feathers 有什么想法吗?
- python-3.x - fetchall 方法将 Postgresql timestamptz 字段转换为不同的时区
- c++ - 默认情况下停用预编译的标头 Visual Studio C++
- tensorflow - mobilenet迁移学习后验证准确率低
- r - read.csv() 中的非英文字符 - R
- c - printf() 精度
- apache-nifi - Apache Nifi中PutHBaseRecord中具有多个字段的行标识符
- amazon-web-services - “kubectl”未从我的本地 Windows 工作站连接到 aws EKS 集群
- javascript - 如何在 Jasmine 的单元测试中模拟 super.ngOnInit()?如何在基类/父类方法上创建间谍以仅涵盖派生/子类代码?