【问题标题】:Array nested struct initialization数组嵌套结构初始化
【发布时间】:2020-08-20 17:52:03
【问题描述】:

还有其他关于初始化嵌套结构数组的帖子。但是,遵循 Stackoverflow 其他地方的给定建议和指向 Aggregate Initialization 的链接并不能帮助我解决问题。

我的上下文是我在 Vulkan 图形 API 中初始化许多嵌套结构。

但是,在查看其他代码进行解释时,我遇到了以下“C”初始化(请注意,我正在添加定义的结构和相关代码)

Vulkan 类型定义

typedef union VkClearColorValue {
    float       float32[4];
    int32_t     int32[4];
    uint32_t    uint32[4];
} VkClearColorValue;

typedef struct VkClearDepthStencilValue {
    float       depth;
    uint32_t    stencil;
} VkClearDepthStencilValue;

typedef union VkClearValue {
    VkClearColorValue           color;
    VkClearDepthStencilValue    depthStencil;
} VkClearValue;

有问题的“C”代码

    const VkClearValue clear_values[2] = {
            [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
            [1] = {.depthStencil = {demo->depthStencil, 0}},
    };

“C”表示在 C99 和最新的 gcc 编译器中是合法的。

但是,当我将它应用到 C++ 时,我得到了错误。

回到聚合初始化的规则,“C”表示在 C++17 中应该是合法的。但是,在编译时,我得到了错误:error: expected primary-expression before '.'令牌

显然我的假设是错误的。因此,谁能提供有关如何在 C++17 中使其合法的指导。

【问题讨论】:

    标签: c++ struct nested initialization


    【解决方案1】:

    回到聚合初始化的规则,“C”表示在 C++17 中应该是合法的

    你的假设是错误的,因为你的结论是正确的。自第一个标准版本以来,C++ 已经进行了聚合初始化,但它不支持在 C99 中添加的所有初始化。例如,指定的初始化器根本不在 C++17 中。

    因此,普通联合只能在第一个活跃成员的情况下初始化,就像在 C89 中一样。要激活另一个成员,必须在初始化后对其进行分配。要使用 const 对象执行此操作,您可以使用函数。


    C++20 添加了指定的初始化器,但即便如此,也只允许使用 C 的子集。以下在 C++20 中格式正确:

    const VkClearValue clear_values[2] = {
        {.color {.float32 = {0.2f, 0.2f, 0.2f, 0.2f}}},
        {.depthStencil = {42, 0}},
    };
    

    【讨论】:

      【解决方案2】:

      这不是 c++ 中aggregate initialization 的有效形式,即使它在 c 中也是如此。其实有一个说明:

      注意:乱序指定初始化、嵌套指定初始化、指定初始化和正则初始化混合、数组的指定初始化在C编程语言中都支持,但在C++中是不允许的。

      struct A { int x, y; };
      struct B { struct A a; };
      struct A a = {.y = 1, .x = 2}; // valid C, invalid C++ (out of order)
      int arr[3] = {[1] = 5};        // valid C, invalid C++ (array)
      struct B b = {.a.x = 0};       // valid C, invalid C++ (nested)
      struct A a = {.x = 1, 2};      // valid C, invalid C++ (mixed)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多