gpt4 book ai didi

c++ - 使用指定的初始化程序对匿名结构进行聚合初始化

转载 作者:行者123 更新时间:2023-12-01 14:52:08 25 4
gpt4 key购买 nike

我正在移植旧的 C++ 代码以使用 GCC 9.2。使用 C++20 和 GNU 扩展是有效的选项。
遗留代码大量使用嵌套在 union 中的匿名结构,并使用指定的初始化聚合初始化,例如:

union u 
{
int a;
struct
{
int b;
int c;
};
};
u f = { .b = 1, .c = 2 };
这个例子做 compile with clang -std=gnu++2a -Wall -Wextra ,但它没有 compile with g++ -std=gnu++2a -Wall -Wextra :

error: too many initializers for 'u'


由于在代码中应用此类构造的情况很多,因此有必要以自动方式(例如在正则表达式的帮助下)对代码应用潜在的更改。如何通过以自动方式并尽可能少地更改代码来使用 GCC 9.2 编译“此代码”?

最佳答案

通过将嵌套结构移动到 union 中的第一个位置并像非匿名结构一样初始化该结构 compiles with g++ -std=gnu++2a -Wall -Wextra :

union u { 
struct
{
int b;
int c;
};
int a;
};
u f = { {.b = 1, .c = 2 } };
应该可以检测到所有匿名 struct s 内 union s 在 union 中带有正则表达式的定义。但是我没有看到如何使用正则表达式来适本地修改列表初始化。

关于c++ - 使用指定的初始化程序对匿名结构进行聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62694003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com