以下作品:
struct
{
int v;
} vals[] = { {1}, {2} };
我可以做同样的事情,而是初始化一个 std::array
吗?
编辑,因为很多人都在问“为什么”
有一些非常明显的解决方法(在评论中列出),但我只想使用该类型一次,所以我真的不想将它添加到我当前的命名空间中。我可以使用元组或类似的东西,但使用命名值可以提高清晰度。如果我正在构造一个 std::array
,我不需要 c 数组值,所以我不能使用 decltype。
我想要做的最干净的解决方案是:
struct
{
int v;
} std::array vals = { {1}, {2} };
还有一个学术兴趣的因素——“这是否可能以某种我没有想到的方式实现?”。好像不是,所以我可能会使用:
struct
{
int v;
} c_array[] = {};
std::array<std::remove_reference_t<decltype(c_array[0])>, 2> arr = { {1}, {2} };
最佳答案
你做不到的原因:
std::array<struct {int v}, 10> arr;
是因为 N4140 的以下规则:
§7.1.6/3 [...] A type-specifier-seq shall not define a class or enumeration unless it appears in the type-id of an alias-declaration (7.1.3) that is not the declaration of a template-declaration.
由于模板类型参数是使用 type-id 指定的,并且 type-id 包含 type-specifier-seq,它不能是类的定义。
您可以使用 typedef,但是:
§9.1/5 A typedef-name (7.1.3) that names a class type, or a cv-qualified version thereof, is also a class-name. [...]
我会接受 T.C. 的建议:
struct { int v; } foo; std::array<decltype(foo), 10> bar = {{{1},{2}}};
关于c++ - 是否可以初始化未命名结构的 std::array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28495119/