c++ - 是否可以初始化未命名结构的 std::array?

标签 c++

以下作品:

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/

相关文章:

C++ opencv编译错误-Windows7 64位使用Eclipse CDT

c++ - 运行已编译的 .exe 时停止打开命令提示符

c++ - "using Time = cppClassDefinition<withT>"的 Cython 等价物

c++ - '晶圆厂' : ambiguous call to overloaded function when using templates

c++ - 如何在不出现 C2227 错误的情况下调用此方法?

c++ - 如何为服务器处理标记TCP?

c++ - 返回 std::string 的函数在没有 return 语句的情况下崩溃,这与返回 int 且没有 return 语句的函数不同

c++ - 错误 C2440 : 'return' : cannot convert from 'int [2]' to 'int (&&)[2]'

c++ - 我应该使用 boost 快速池分配器进行跟踪吗?

c++ - 修改大型动态大小的 3D 数组 mex/C++